Jquery “动画”按预期停止滚动。有线索吗?
这是小提琴: 查看问题的步骤:Jquery “动画”按预期停止滚动。有线索吗?,jquery,jquery-animate,Jquery,Jquery Animate,这是小提琴: 查看问题的步骤: 点击“ble”菜单项 在黄色部分内单击 点击“bla bla”菜单项 再次单击“ble”菜单项 你会注意到这一步不起作用,我们也不会卷回那个项目,因为我相信我们已经更改了ID var $root = $('html, body'); $('.main-menu a').click(function() { $root.animate({ scrollTop: $($(this).attr('href')).offset().top+1 }, 2000
var $root = $('html, body');
$('.main-menu a').click(function() {
$root.animate({
scrollTop: $($(this).attr('href')).offset().top+1
}, 2000
);
return false;
});
我曾尝试过多次更改此代码,但我一无所获,因此我最终放弃发布垃圾,只留下问题代码
是否有人可以就如何修复此行为提供建议?您正在根据单击时元素的id检查元素的偏移量。因此,如果更改该id,下次单击时,查询
$($(this.attr('href'))
将失败(它不再匹配任何内容)。因此,.offset().top
不会是导致动画失败的数字
若要修复此问题,请在单击侦听器外部获取偏移量,这样您就不会在单击时查询,将来的单击只会绑定到原始偏移量
var $root = $('html, body');
$('.main-menu a').each(function(){
// capture the offset on init not click
var that = $(this),
offset = $(that.attr('href')).offset().top+1;
// then use that offset, so we are not querying for id on each click
that.click(function() {
$root.animate({
scrollTop: offset
}, 2000);
});
});