javascript - scrollTo scrolls to the top of the page - Stack Overflow

I have the following Javascript code.When the page is loaded it is scrolled to the right position. When

I have the following Javascript code.

When the page is loaded it is scrolled to the right position. When I click on the link to run the function the page scrolls to the top of the page.

How do I fix this?

<html>
    <head>
        <script  type="text/javascript">
            function scroll() {
                window.scrollTo(0, 400)
            }
        </script>
        <title></title>
    </head>
    <body onload="window.scrollTo(0, 400)">
        <img src="a.jpg"/>
        <a href="#" onclick="scroll">ments1</a>
    </body>
</html>

I have the following Javascript code.

When the page is loaded it is scrolled to the right position. When I click on the link to run the function the page scrolls to the top of the page.

How do I fix this?

<html>
    <head>
        <script  type="text/javascript">
            function scroll() {
                window.scrollTo(0, 400)
            }
        </script>
        <title></title>
    </head>
    <body onload="window.scrollTo(0, 400)">
        <img src="a.jpg"/>
        <a href="#" onclick="scroll">ments1</a>
    </body>
</html>
Share Improve this question edited Mar 10, 2012 at 20:28 Jon Adams 25.2k18 gold badges84 silver badges121 bronze badges asked Mar 27, 2010 at 21:04 johnkjohnk 4001 gold badge4 silver badges15 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

Use

onclick="scroll(); return false;"

that should fix it.

To add a bit more detail, with the return false;, the click event continues after the page is scrolled, and the click event follows the href to #, which is the top of the page. An alternative way to fix this is:

<a href="javascript:void(0);" onclick="scroll">ments1</a>

Returning false is better, IMO, but this would also do the trick.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742347853a4426909.html

相关推荐

  • javascript - scrollTo scrolls to the top of the page - Stack Overflow

    I have the following Javascript code.When the page is loaded it is scrolled to the right position. When

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信