scrollTo 滚动到页面顶部

发布于 2024-08-26 10:00:33 字数 541 浏览 3 评论 0原文

我有以下 JavaScript 代码。

当页面加载时,它会滚动到正确的位置。当我单击链接运行该函数时,页面滚动到页面顶部。

我该如何解决这个问题?

<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">comments1</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">comments1</a>
    </body>
</html>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

非要怀念 2024-09-02 10:00:33

使用

onclick="scroll(); return false;"

它应该可以修复它。

Use

onclick="scroll(); return false;"

that should fix it.

枕头说它不想醒 2024-09-02 10:00:33

再补充一点细节,通过return false;,页面滚动后点击事件继续,点击事件跟随href#< /code>,这是页面的顶部。解决此问题的另一种方法是:

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

返回 false 更好,IMO,但这也可以解决问题。

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">comments1</a>

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文