$('.mainNav a[href^="#"]').on('click', function (event) {
var target = $(this.getAttribute('href'));
if (target.length) {
event.preventDefault();
$('body').stop(true).animate({
scrollTop: target.offset().top - 130
}, 1000);
}
return false;
});
我尝试使用 preventDefault()
但仍然闪烁
最佳答案
这是我会做的:
- 你不需要 return false 因为你使用了 preventDefault()
并且你应该把它放在任何条件语句之前
- 你不需要 stop()
函数中的 true
- 你应该使用 $('html, body')
而不是 $('body')
$('.mainNav a[href^="#"]').on('click', function (event) {
var target = $($(this).attr('href'));
event.preventDefault();
if (target.length){
$('html, body').stop().animate({
scrollTop: target.offset().top - 130
}, 1000);
}
});
但如果它不能解决您的问题,也许可以做一个 jsfiddle 或 codepen 来向我们展示?因为闪烁可能是由于脚本本身以外的其他因素造成的。
关于javascript - 使用动画和滚动时闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38722424/