【问题标题】:How do I make the SVG Object clickable and scroll to anchor using jQuery?如何使用 jQuery 使 SVG 对象可点击并滚动到锚点?
【发布时间】:2017-03-17 20:06:50
【问题描述】:

我的 SVG 是通过一个对象标签嵌入的,并且还有 CSS3 悬停动画。尝试将 SVG 与悬停动画超链接会弄乱指针或单击操作。我没有将长 SVG 路径代码用于代码组织偏好。

下面的这个 JavaScript 使它可以点击,但它不会转到所需的锚点 # 以便稍后在页面中滚动。 你知道如何结合这两个点击功能吗?

这很乱,我知道!

HTML

<object id="example" type="image/svg+xml" data="/images/icon.svg"> </object>

SVG 内部:

<a xlink:href="#top">
    <g class="whole" fill="#fff">
        <rect id="body" x="113.83" y="185.4" width="43" height="49.5" style="stroke:#f36a24;stroke-miterlimit:10;stroke-width:3px" />
        <ellipse id="head" cx="134.96" cy="165.04" rx="14.13" ry="13.92" style="stroke:#f36a24;stroke-miterlimit:10;stroke-width:3px" />
    </g>
</a>

//下面的JS

<script>
       (function ($) {
           $(document).ready(function () {
               $('svg a').click(function (event) {
                   alert(event.target.parentElement.tagName);
               });
           });
       })(jQuery);

</script>

<script>
    $(function () {
        $('a[href*="#"]:not([href="#"])').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });
</script>

【问题讨论】:

    标签: javascript jquery css svg


    【解决方案1】:

    正如您所说,单击有效,为了滚动到另一个锚点,还需要完成一个步骤。只需在点击事件时执行以下代码sn -p即可。

    $('html, body').animate({
          'scrollTop':   $('#scrollTo').offset().top
    }, 2000);
    

    检查这个例子https://jsfiddle.net/q70jq0kt/1/

    【讨论】:

    • 感谢您的回答。我有 5 个 svg 图标。每个都有一个 CSS 悬停动画,每个都有一个锚点 ID,一旦点击,它就会滚动到页面下方的一个部分。所以我不想写一个确切的ID。所以jQuery可以应用于所有svgs,它应该只是说$('#')还是什么?
    • 你可以做的是,保留一个数据属性来保存你想要滚动到的锚点的 id。然后在点击事件中读取该值并滚动到该元素。 $('object').on('click', function () { var scroll = $(this).data('scroll') $('html, body').animate({ 'scrollTop': $(' #' + scroll).offset().top }, 2000); });如果没看懂请看这个示例。jsfiddle.net/87q5y0zx
    • 如果它解决了你的问题,为什么不使用投票:)
    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2018-12-22
    相关资源
    最近更新 更多