![](/img/trans.png)
[英]How to prevent Leaflet from scrolling the page when clicking the zoom buttons?
[英]How to Prevent the Exit Popup From Showing When Clicking “INPUT” Buttons?
简介/免责声明:是的,我知道这很糟糕。 是的,我已经让客户知道了我的想法。 不,我永远不会在自己的网站上这样做。 我讨厌这个概念。 但是,有时您需要做的是让客户在其网站的测试版本上亲自查看用户体验如何受到损害,该做些什么。
在某些合理的情况下,诸如功能是有用的,例如可以防止数据丢失。 如果您在发布问题或答案时不小心导航到另一个页面,StackOverflow使用退出弹出窗口来提示您保存数据。
话虽如此,让我们继续前进。
问题描述:
我有一个正在运行的JavaScript函数,位于Snipplr上-确认将网站保留为onbeforeunload 。
window.onload = function(){
var allowUnload = true;
window.onbeforeunload = function(e){
//allowUnload will allow us to see if user recently clicked something if so we wont allow the beforeunload.
if(allowUnload){
//message to be returned to the popup box.
var message = 'Are you sure you want to leave this page message',
e = e||window.event;
if(e)
e.returnValue=message; // IE
return message; // Safari
}
};
// We need this to allow us to see if user has clicked anywhere if user has clicked we wont allow beforeunload to run.
document.getElementsByTagName('body')[0].onclick = function(){
allowUnload = false;
//setTimeout so we can reset allowUnload incase user didn't leave the page but randomly clicked.
setTimeout(function(){ allowUnload = true; },100);
};
};
如果用户单击页面上的超链接,该代码段将阻止显示“退出弹出窗口”。 退出弹出窗口会显示自己以进行F5刷新,以及用户离开站点时。 这是所需的行为,只有一个例外。
如果我单击包含一个onclick事件的按钮,该事件用新的链接替换了parent.location,则退出弹出窗口将触发:
<input type="button" onclick="parent.location = '/test.html';" />
我需要在代码段中添加些什么以防止单击此按钮启动“退出弹出窗口”?
约束如下:
经过几个小时的搜索和故障排除,我想出了解决此问题的方法:
var button_element = document.getElementsByTagName('input')['button_name'];
// get old onclick attribute
var onclick = button_element.getAttribute("onclick");
// if onclick is not a function, it's not IE7, so use setAttribute
if(typeof(onclick) != "function") {
button_element.setAttribute('onclick','allowUnload = false;' + onclick); // for FF,IE8,Chrome
// if onclick is a function, use the IE7 method and call onclick() in the anonymous function
} else {
button_element.onclick = function() {
allowUnload = false;
onclick();
}; // for IE7
}
在IE7中,getAttribute(“ onclick”)返回一个函数,但是在所有其他浏览器中,它只是文本字符串。 我不想使用eval,但是由于有了有关如何动态绑定onclick事件的答案 ,我得以在所有浏览器中实现此目的。
我还必须通过检查onclick变量是否为确定使用哪种方法的函数来使用功能检测,因为这两种方法在一起是不兼容的。
现在,当我单击IE7,IE8,IE9,FF和Chrome中的输入按钮时,页面将正确重定向,而不会显示退出弹出窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.