javascript 带有 onclick 和 href='#' 的锚标签滚动到顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3553135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:30:13  来源:igfitidea点击:

Anchor tag with onclick and href='#' scrolls to top

javascripthtml

提问by stupidkid

I have an anchor tag

我有一个锚标签

<a href="#" onclick="Register();" >Register</a>

If you don't have a href in you anchor, it can screw up some stuff, but I don't need to redirect, just call a js function. When this link is clicked however, the href="#" causes it to scroll the page to the top. How do I prevent that from happening?

如果你的锚中没有 href ,它可能会搞砸一些东西,但我不需要重定向,只需调用一个 js 函数。但是,当单击此链接时, href="#" 会使其将页面滚动到顶部。我如何防止这种情况发生?

回答by Nick Craver

You can add a return false;, like this:

您可以添加一个return false;,如下所示:

<a href="#" onclick="Register(); return false;">Register</a>

This prevents the default action of the anchor, which is to go to the hash, causing the scroll.

这可以防止锚点的默认操作,即转到散列,从而导致滚动。

回答by sweets-BlingBling

Use:

利用:

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

javascript:void(0) will prevent the page from getting redirected and also will fix the issue where your page is getting scrolled on top due to href="#"

javascript:void(0) 将阻止页面被重定向,并且还将解决由于 href="#" 导致页面滚动到顶部的问题