javascript 点击后防止页面滚动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7697917/
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
Prevent page scroll after click?
提问by Jennifer Anthony
After clicking on the link, Click Me
, the page scrolls back to the top. I do not want this. How can fix it?
单击链接后Click Me
,页面会滚动回到顶部。我不想要这个。如何解决?
Example:http://jsfiddle.net/Y6Y3Z/
示例:http : //jsfiddle.net/Y6Y3Z/
Scroll-bar:
滚动条:
function myalert() {
var result = true;
//var hide = $('.alert').fadeOut(100);
//var css = $('#appriseOverlay').css('display','none');
var $alertDiv = $('<div class="alert">Are you sure you want to delete this item?<div class="clear"></div><button class="ok">no</button><button class="cancel">yes</button></div>');
var link = this;
$('body').append($alertDiv);
$('.ok').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
callback(true, link);
});
$('.cancel').click(function () {
$('.alert').fadeOut(100);
$('#appriseOverlay').css('display', 'none');
callback(false, link);
});
$alertDiv.fadeIn(100);
$('#appriseOverlay').css('display', 'block');
return result;
};
$('.click').click(myalert);
function callback(result, link) {
//
if(result){
}
}
回答by tvanfosson
The reason that it is going to the top of the page is because your anchor tag has a hash symbol as the href. The hash syntax allows you to refer to a named anchor in the document, with the link taking you to that place in the document. The default action for an anchor tag when you click on it and the href refers to a named anchor that doesn't exist is to go to the top of the page. To prevent this cancel the default action by returning false from the handler or using preventDefault
on the event.
它进入页面顶部的原因是你的锚标签有一个哈希符号作为href。散列语法允许您引用文档中的命名锚点,链接会将您带到文档中的该位置。当您单击锚标记并且 href 引用不存在的命名锚时,锚标记的默认操作是转到页面顶部。为了防止这种情况,通过从处理程序返回 false 或preventDefault
在事件上使用来取消默认操作。
function myalert(e) {
e.preventDefault(); // <-- prevent the default action
...
return false; // <-- alternative way to prevent the default action.
};
回答by Gilberto Sánchez
You only need to change the "#" to "javascript:void(0)" on HTML code:
您只需要将 HTML 代码中的“#”更改为“javascript:void(0)”:
<a href="javascript:void(0)" class="click">Click Me</a>
Another solution is add a "/" after the "#":
另一种解决方案是在“#”后添加“/”:
<a href="#/" class="click">Click Me</a>
回答by rodneyrehm
simply prevent the default function (jump to #marker) from executing: http://jsfiddle.net/Y6Y3Z/1/
简单地防止默认函数(跳转到#marker)执行:http: //jsfiddle.net/Y6Y3Z/1/