当与 jquery slidetoggle 一起使用时,带有 href="#" 的链接将页面滚动到顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2024342/
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
link with href="#" scrolls page to top when used with jquery slidetoggle
提问by samoyed
Possible Duplicate:
How do I stop a web page from scrolling to the top when a link is clicked that triggers javascript?
I'm using jquery's slidetoggle to show/hide divs. the element that controls the sliding is a text link ( some text inside <\a>) which has href="#" so it will look like a link (underline, cursor change).
我正在使用 jquery 的 slidetoggle 来显示/隐藏 div。控制滑动的元素是一个带有 href="#" 的文本链接(<\a> 中的一些文本),因此它看起来像一个链接(下划线、光标更改)。
the problem is that when the link is clicked, in addition to the sliding effect, the page scrolls to top.
问题是当点击链接时,除了滑动效果,页面滚动到顶部。
i tried replacing href="#" with href="" but that disables the div show/hide effect. i guess i could add to the tag Name="somename" and then set the href to href="#somename" but i would rather not use tricks like that.
我尝试用 href="" 替换 href="#" 但这会禁用 div 显示/隐藏效果。我想我可以添加到标签 Name="somename" 然后将 href 设置为 href="#somename" 但我宁愿不使用这样的技巧。
why is href="#" scrolling the page to its top?
为什么 href="#" 将页面滚动到顶部?
any ideas would be highly appreciated
任何想法将不胜感激
回答by rfunduk
Several options:
几个选项:
- Put
return false;
at the bottom of your click handler and the href wont be followed. - Change the href to
javascript:void(0);
Call
preventDefault
on the event in your handler:function( e ) { e.preventDefault(); // your event handling code }
- 放在
return false;
点击处理程序的底部,href 不会被跟随。 - 将 href 更改为
javascript:void(0);
preventDefault
在处理程序中调用事件:function( e ) { e.preventDefault(); // your event handling code }
回答by SLaks
You need to add return false;
to your click handler.
This will prevent the browser from executing the default action for the click.
您需要添加return false;
到您的点击处理程序。
这将阻止浏览器执行点击的默认操作。
回答by slebetman
Others have given you solutions. But to specifically answer your question, #
refers to the current page. And since the interpretation of tags is to bring the topof the tag into view, clicking on a #
tag scrolls you to the top of the current page.
其他人已经给了你解决方案。但要具体回答您的问题,#
请参阅当前页面。由于标签的解释是将标签的顶部带入视野,因此单击标签会将#
您滚动到当前页面的顶部。
回答by Russ Cam
return false
or event.preventDefault()
are what you need in your click event handler to prevent the default action from occurring. An <a>
element with a href
of #
will cause the browser viewport to jump to the top of the page as the default action
return false
或者event.preventDefault()
是您在单击事件处理程序中需要的内容,以防止发生默认操作。<a>
带有href
of的 元素#
将导致浏览器视口作为默认操作跳转到页面顶部