javascript 页面加载后需要javascript自动滚动到目标html元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5013281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Need javascript to auto-scroll to the target html element after page loads
提问by Jason
I'm backend developer, new to javascript. Can anyone provide a few lines of script that will allow the page to auto-scroll to the "target" element after the page loads
我是后端开发人员,JavaScript 新手。任何人都可以提供几行脚本,允许页面在页面加载后自动滚动到“目标”元素
<html>
<bod>
<p id="target">...</p> // auto-scroll here
</bod>
</html>
Thanks
谢谢
回答by Yoeri
You can use scrollIntoView on the element in window.onload event..
您可以在 window.onload 事件中的元素上使用 scrollIntoView ..
In your case you would be doing:
在您的情况下,您将执行以下操作:
window.onload = function() {
var el = document.getElementById('target');
el.scrollIntoView(true);
}
Good docs can be found here: MDN scrollIntoView
可以在这里找到好的文档: MDN scrollIntoView
回答by Ken Wayne VanderLinde
Also change your body tag to something like
还将您的身体标签更改为
<body onload="ScrollToTarget">
Then your function can be defined in the header as
然后你的函数可以在标题中定义为
function ScrollToTarget()
{
document.getElementById("target").scrollIntoView(true);
}

