How do I stop a web page from scrolling to the top

2019-01-01 00:40发布

When I have a link that is wired-up with a jQuery or JavaScript event such as:

<a href="#">My Link</a>

How do I prevent the page from scrolling to the top? When I remove the href attribute from the anchor the page doesn't scroll to the top but the link doesn't appear to be click-able.

15条回答
初与友歌
2楼-- · 2019-01-01 01:09

You might want to check your CSS. In the example here: https://css-tricks.com/the-checkbox-hack/ there's position: absolute; top: -9999px;. This is particularly goofy on Chrome, as onclick="whatever" still jumps to the absolute position of the clicked element.

Removing position: absolute; top: -9999px;, for display: none; might help.

查看更多
何处买醉
3楼-- · 2019-01-01 01:13

You should change the

<a href="#">My Link</a>

to

<a href="javascript:;">My Link</a>

This way when the link is clicked the page won't scroll to top. This is cleaner than using href="#" and then preventing the default event from running.

I have good reasons for this on the first answer to this question, like the return false; will not execute if the called function throws an error, or you may add the return false; to a doSomething() function and then forget to use return doSomething();

查看更多
唯独是你
4楼-- · 2019-01-01 01:16

If you can simply change the href value, you should use:

<a href="javascript:void(0);">Link Title</a>

Another neat solution I just came up with is to use jQuery to stop the click action from occurring and causing the page to scroll, but only for href="#" links.

<script type="text/javascript">
    /* Stop page jumping when links are pressed */
    $('a[href="#"]').live("click", function(e) {
         return false; // prevent default click action from happening!
         e.preventDefault(); // same thing as above
    });
</script>
查看更多
登录 后发表回答