我试图(在某种程度上)使用原生javascript模拟平滑滚动。我非常接近我想要的东西,但我的逻辑一直滚动到页面底部[LINK TO PAGE]。您可以单击“其他工作”链接以查看当前的滚动行为,并打开控制台以查看调试语句。
<script type="text/javascript">
var el = document.querySelector('a[href="#other-works"]');
var otherEl = document.querySelector('#other-works')
el.onclick = function () {
var i = 0;
var distance = otherEl.offsetTop - document.body.scrollTop;
console.log("distance: ", distance);
var pixelJump = 25;
(function loop() {
console.log("i: ",i);
console.log("current scrollTop: ", document.body.scrollTop)
if (i + pixelJump > distance) {
document.body.scrollTop = otherEl.offsetTop;
console.log('its over')
return;
}
if (i > distance) return;
i += pixelJump;
scrollBy(0, pixelJump);
console.log("new height: ", document.body.scrollTop)
setTimeout(loop, 50);
})();
}
</script>
我已经添加了console.log语句来尝试和调试。以下是输出示例:
scroll distance required: 2910
i: 0
current scrollTop: 478
new height: 503
i: 25
current scrollTop: 3388 ##### Why does scrollTop jump to 3388??? #######
new height: 3413
i: 50
current scrollTop: 3413
new height: 3438
i: 75
答案 0 :(得分:-1)