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

JavaScript scroll to y position - Stack Overflow

programmeradmin2浏览0评论

does anybody know why scrolling of scrollbar to y position does not work? Very simple code below. In JSFiddle it works fine. I don't see any reason why it should not work. Scroll bar appears but still at the top :-(

<script>
 window.scrollTo(50,100);
</script>

<body>
    <div style="width:200px; height:1500px;background-color:blue;">
        hello
    </div>
</body>

does anybody know why scrolling of scrollbar to y position does not work? Very simple code below. In JSFiddle it works fine. I don't see any reason why it should not work. Scroll bar appears but still at the top :-(

<script>
 window.scrollTo(50,100);
</script>

<body>
    <div style="width:200px; height:1500px;background-color:blue;">
        hello
    </div>
</body>

Share Improve this question asked Nov 15, 2013 at 7:53 Lukáš JežekLukáš Ježek 751 gold badge3 silver badges12 bronze badges 2
  • 1 Have you tried putting the <script> element at the bottom of the page, before the end of <body>? – J. Holmes Commented Nov 15, 2013 at 7:57
  • Your script is executed before the DOM is loaded. – Derek 朕會功夫 Commented Nov 15, 2013 at 8:34
Add a ment  | 

2 Answers 2

Reset to default 4

You need to put the script block below the div and attach the scrollTo to the windows onload event for this to scroll down on page load.

Try this:

<body>
    <div id="div1" style="width:200px; height:1500px;background-color:blue;">
        hello
    </div>
    <script>
        window.onload = function() { window.scrollTo(50,100); };
    </script>
</body>

Script must be executed after all DOM elements are created so use window.onload method for javascript and $(document).ready() for jQuery

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

    <script>
        window.onload = function () {
            window.scrollTo(50, 100);
        }
    </script>
</head>
<body>
    <div style="width:200px; height:1500px;background-color:blue;">
        hello
    </div>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论