我的平滑滚动js不能触发动画?

3

我不懂这是怎么回事,页面只是跳到了ID位置,没有动画效果。同时警告“click”的内容也没有显示?

<script>
jQuery(document).ready(function($) {
   alert('start');
    $('ul#menu-sde-menu li a[href^="#"]').on('click', function(event) {
        alert("click");
        var target = $(this.getAttribute('href'));

        if (target.length) {
            event.preventDefault();
            $('html, body').stop().animate({
                scrollTop: target.offset().top
            }, 1000);
        }

    });
});

一个简单的菜单

<ul id="menu-sde-menu"><li><a href="http://localhost/testdomain/sde/#link1">link 1</a></li><li><a href="http://localhost/testdomain/sde/#link2">link 2</a></li></ul>

我尝试使用https://www.abeautifulsite.net/smoothly-scroll-to-an-element-without-a-jquery-plugin-2来平滑地滚动到一个元素。

1个回答

1

不要使用绝对路径 http://localhost/testdomain/sde/#link2

简单地说:

href="#link2"

(if you're planning to stay on the same page anyways, logically.) (如果你打算逻辑上留在同一页。)
You're using a[href^="#"] - which means get elements having href attribute which starts with ^= an #, and http:// is clearly not one. (您正在使用a [href ^ =“#”] - 这意味着获取具有href属性的元素,该属性以#开头,并且http://显然不是其中之一。)

啊,我明白了,谢谢。我正在使用WordPress,并且我确实有绝对路径,而不仅仅是锚点。 - alex

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接