我想(有點)模仿使用本機JavaScript的平滑滾動。我非常接近我想要的,但是我的邏輯一直滾動到頁面底部[LINK TO PAGE]。您可以單擊「其他作品」鏈接查看當前的滾動行爲並打開控制檯以查看調試語句。JavaScript同步setTimeout使用IIFE
<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
請在問題本身而不是第三方網站上提供[mcve]中的所有相關代碼。 –