问题是它一直无休止地滚动,我试图使用 exit 终止它,但它不起作用,有什么解决方案吗?
了解更多
<script>
var marginY = 0;
var destination= 0;
var speed = 10;
var scroller = null;
function initScroll(elementId)
{
destination= document.getElementById(elementId).offsettop;
scroller = setTimeout(function(){initScroll(elementId);},1);
marginY = marginY + speed;
if(marginY >= destination)
{
clearTimeout(scroller);
}
window.scroll(0,marginY);
}
</script>
最佳答案
JavaScript 区分大小写!它是 offsetTop
而不是 offsettop
:
destination = document.getElementById(elementId).offsetTop;
<小时/>
另一方面,我不确定这是如何运作的。如果您正在尝试平滑滚动,您还可以通过以下方式使用 jQuery:
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
关于javascript - setTimeout 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33984600/