可能的重复:
当点击触发 JavaScript 的链接时,如何阻止网页滚动到顶部?
我正在使用 jquery 的 Slidetoggle 来显示/隐藏 div。
控制滑动的元素是一个文本链接(<\a> 内有一些文本)
其中有 href="#" 所以它看起来像一个链接(下划线,光标变化)。
问题是,点击链接时,除了滑动效果之外,
页面滚动到顶部。
我尝试用 href="" 替换 href="#" 但这会禁用 div 显示/隐藏效果。
我想我可以添加到标签 Name="somename" ,然后将 href 设置为 href="#somename"
但我宁愿不使用这样的技巧。
为什么 href="#" 将页面滚动到顶部?
任何想法将不胜感激
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).
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.
why is href="#" scrolling the page to its top?
any ideas would be highly appreciated
发布评论
评论(4)
几个选项:
return false;
放在点击处理程序的底部,这样 href 就不会被跟随。javascript:void(0);
在处理程序中的事件上调用
preventDefault
:Several options:
return false;
at the bottom of your click handler and the href wont be followed.javascript:void(0);
Call
preventDefault
on the event in your handler:您需要将
return false;
添加到您的点击处理程序中。这将阻止浏览器执行点击的默认操作。
You need to add
return false;
to your click handler.This will prevent the browser from executing the default action for the click.
其他人已经给你解决方案了。但为了具体回答您的问题,
#
指的是当前页面。由于标签的解释是将标签的顶部带入视图,因此单击#
标签会将您滚动到当前页面的顶部。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 top of the tag into view, clicking on a#
tag scrolls you to the top of the current page.您在点击事件处理程序中需要使用
return false
或event.preventDefault()
来防止发生默认操作。href
为#
的元素将导致浏览器视口跳转到页面顶部作为默认操作
return false
orevent.preventDefault()
are what you need in your click event handler to prevent the default action from occurring. An<a>
element with ahref
of#
will cause the browser viewport to jump to the top of the page as the default action