这是一个HTML页面,在左上角显示三个正方形div:
<div class="whiteish bigwidth" style="height:100%;">
<div class="square greenish" style="left:50px; top:50px;"></div>
<div class="square redish" style="left:70px; top:70px;"></div>
<div class="square bluish" style="left:90px; top:90px;"></div>
</div>
<style>
.bigwidth {
width: 2000px;
display: block;
}
.square {
width: 100px;
height: 100px;
display: block;
position: absolute;
}
.greenish {
background-color: #75af99;
}
.redish {
background-color: #ff9b98;
}
.bluish {
background-color: #aabbff;
}
.whiteish {
background-color: #eaeaea;
}
* {
padding: 0;
margin: 0;
}
</style>
<script>
window.addEventListener('load', function () {
console.log('load event has fired')
window.scrollTo(500, 0);
// setTimeout(function() { window.scrollTo(500, 0); }, 0);
})
</script>
目前,页面加载时发生的window.scrollTo(500, 0);
命令无效(在Safari和Chrome中测试)。但是,如果我们用行代替它
setTimeout(function() { window.scrollTo(500, 0); }, 0);
(在上面的代码中有注释),滚动确实发生了。为什么会这样?