页面加载后需要javascript自动滚动到目标html元素

Jas*_*son 6 javascript

我是后端开发人员,是javascript的新手.任何人都可以提供几行脚本,允许页面在页面加载后自动滚动到"target"元素

<html>
<bod>

<p id="target">...</p> // auto-scroll here

</bod>
</html>
Run Code Online (Sandbox Code Playgroud)

谢谢

Yoe*_*eri 9

您可以在window.onload事件中的元素上使用scrollIntoView.

在你的情况下,你会做:

window.onload = function() {
    var el = document.getElementById('target');
    el.scrollIntoView(true);
}
Run Code Online (Sandbox Code Playgroud)

可以在这里找到好的文档: MDN scrollIntoView