最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Need javascript to auto-scroll to the target html element after page loads - Stack Overflow

programmeradmin4浏览0评论

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

<html>
<bod>

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

</bod>
</html>

Thanks

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

<html>
<bod>

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

</bod>
</html>

Thanks

Share Improve this question asked Feb 16, 2011 at 6:40 JasonJason 1011 gold badge1 silver badge3 bronze badges 1
  • Can you please mark a correct answer. – hitautodestruct Commented Jan 1, 2014 at 9:51
Add a comment  | 

2 Answers 2

Reset to default 13

You can use scrollIntoView on the element in window.onload event..

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

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);
}
发布评论

评论列表(0)

  1. 暂无评论