使用onclick和href ='#'的锚标记滚动到顶部

时间:2022-11-27 18:00:09

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 =“#”会使页面滚动到顶部。我该如何防止这种情况发生?

2 个解决方案

#1


11  

You can add a return false;, like this:

您可以添加返回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.

这可以防止锚的默认操作,即锚定,导致滚动。

#2


8  

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 =“#”而导致页面滚动到顶部的问题

#1


11  

You can add a return false;, like this:

您可以添加返回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.

这可以防止锚的默认操作,即锚定,导致滚动。

#2


8  

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 =“#”而导致页面滚动到顶部的问题