我没听懂,页面只是跳转到 id 而不是动画。 也没有显示“点击”警报?
<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
最佳答案
不要使用绝对路径http://localhost/testdomain/sde/#link2
简单地:
href="#link2"
(从逻辑上讲,如果您打算无论如何都停留在同一页面上。)
您正在使用 a[href^="#"]
- 这意味着获取具有 href
属性的元素,该属性以 ^=
一个#
,而http://
显然不是一个。
关于javascript - 我的平滑滚动 js 不会触发动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42494080/