当点击触发JavaScript的链接时,如何阻止网页从顶部滚动到顶部? [英] How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?
问题描述
$ b
< a href 当我有一个链接与jQuery或JavaScript事件连接时, =#>我的连结< / a>
如何防止页面滚动到顶部?当我从锚点删除href属性时,页面不会滚动到顶部,但链接看起来不可点击。
有两种方法可以做到这一点。
$ b
选项1: event.preventDefault()
<调用传递给处理程序的事件对象的
.preventDefault()
方法。如果您使用jQuery绑定您的处理程序,则该事件将成为 jQuery.Event
,它将是jQuery版本 .preventDefault()
。如果您使用 addEventListener
来绑定您的处理程序,它将是 Event
和原始DOM版本 .preventDefault()
。 例子:
$ ('#ma_link')。click(function($ e){
$ e.preventDefault();
doSomething();
});
document.getElementById('#ma_link')。addEventListener('click',function(e){
e.preventDefault();
doSomething();
))
选项2:返回false;
在jQuery 中:
从事件处理函数中返回false将自动调用event.stopPropagation()和event.preventDefault()
因此,使用jQuery,您可以使用此方法来阻止默认链接行为:
doSomething();
return false;
});
如果您使用的是原始DOM事件,这也适用于现代浏览器,因为HTML 5规范说明了这种行为。然而,旧版本的规范并没有,所以如果你需要与旧浏览器最大的兼容性,你应该明确地调用 .preventDefault()
。请参阅 event.preventDefault()与返回false(无jQuery)的规格细节。
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.
You need to prevent the default action for the click event (i.e. navigating to the link target) from occurring.
There are two ways to do this.
Option 1: event.preventDefault()
Call the .preventDefault()
method of the event object passed to your handler. If you're using jQuery to bind your handlers, that event will be an instance of jQuery.Event
and it will be the jQuery version of .preventDefault()
. If you're using addEventListener
to bind your handlers, it will be an Event
and the raw DOM version of .preventDefault()
. Either way will do what you need.
Examples:
$('#ma_link').click(function($e) {
$e.preventDefault();
doSomething();
});
document.getElementById('#ma_link').addEventListener('click', function (e) {
e.preventDefault();
doSomething();
})
Option 2: return false;
Returning false from an event handler will automatically call event.stopPropagation() and event.preventDefault()
So, with jQuery, you can alternatively use this approach to prevent the default link behaviour:
$('#ma_link').click(function(e) {
doSomething();
return false;
});
If you're using raw DOM events, this will also work on modern browsers, since the HTML 5 spec dictates this behaviour. However, older versions of the spec did not, so if you need maximum compatibility with older browsers, you should call .preventDefault()
explicitly. See event.preventDefault() vs. return false (no jQuery) for the spec detail.
这篇关于当点击触发JavaScript的链接时,如何阻止网页从顶部滚动到顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!