页面在基本jQuery上闪烁,滚动到元素
我有一个链接,点击后向下滚动到一个元素 每次我测试点击时,页面可能会在滚动前不一致地闪烁 链接:页面在基本jQuery上闪烁,滚动到元素,jquery,html,css,Jquery,Html,Css,我有一个链接,点击后向下滚动到一个元素 每次我测试点击时,页面可能会在滚动前不一致地闪烁 链接: <a id="continue_scroll" href="#welcome">Continue / Scroll</span></a> <h2 id="welcome">WELCOME</h2> jQuery(function($){ $("#continue_scroll").click(function() {
<a id="continue_scroll" href="#welcome">Continue / Scroll</span></a>
<h2 id="welcome">WELCOME</h2>
jQuery(function($){
$("#continue_scroll").click(function() {
$('html, body').animate({
scrollTop: $("#welcome").offset().top
}, 2000);
});
});
行为:当我刷新页面并连续单击“继续”链接或间歇单击之前/之后的其他位置时发生。这种行为前后不一致
任何人都能确定是什么导致了这种情况,以及相应的解决方案是什么吗?您需要防止锚的默认操作(即立即跳转到href'ed元素)
jQuery(函数($){
$(“#继续滚动”)。单击(函数(e){
e、 预防默认值();
$('html,body')。设置动画({
scrollTop:$(“#欢迎”).offset().top
}, 2000);
});
});
您看到的闪现是,在jQuery接管之前,页面立即滚动到
#welcome
,并用动画再次滚动到元素感谢您提供了这个有效的解决方案。我在假设问题更复杂或更相关时忽略了简单。
jQuery(function($){
$("#continue_scroll").click(function(e) { <!-- add a reference to the event here -->
e.preventDefault(); <!-- prevent the default action of the event -->
$('html, body').animate({
scrollTop: $("#welcome").offset().top
}, 2000);
});
});