有人可以帮助我理解为什么这不起作用:
jQuery(".page-code .opening .button").click(function(event){
event.preventDefault();
var id = "#" + event.target.id;
alert(id);
jQuery('html, body').animate({
scrollTop: jQuery(id).offset().top
}, 500);
})
anchor 链接存在于页面的各个部分,警报为我提供了我需要的正确 ID,但无论我单击哪个按钮,页面都只会滚动一点点。不确定我在这里缺少什么。
最佳答案
您将滚动的目标设置为刚刚单击的元素。如果你想滚动到链接指向的元素,你需要使用 href 属性(假设你的按钮是 a
标签):
jQuery(".page-code .opening .button").click(function(event){
event.preventDefault();
var id = "#" + jQuery(this).attr('href');
alert(id);
jQuery('html, body').animate({
scrollTop: jQuery('body').offset().top
}, 500);
})
关于javascript - 变量未传递到 jQuery 滚动函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35922130/