我遇到了一个非常奇怪的问题,只发生在 firefox 中。我有一个常规对话框:
var cnf = confirm(message);
if(cnf) {
blah blah
}
问题是我在文档上还有一个 keyup 处理程序,当用户键入 enter 以确认对话框时,它会以某种方式触发。
$(document).bind('keyup', function(e) {
console.log('someone hit ' + e.which);
});
当用户按下 enter 键确认时,控制台还会记录“someone hit 13”,这在任何其他浏览器中都不会发生(而且 AFAIK 不应该发生)
我有什么办法可以防止 keydown 事件的传播或以某种方式避免这种行为?
这是描述问题的 jsfiddle:clicky
最佳答案
我认为最好的解决方案是覆盖 Firefox 中的确认方法。
// Ideally you should use feature detection but can't think of a better way
if ( true ) { // Check for firefox like $.browser.mozilla
(function(window){
var _confirm = window.confirm;
window.confirm = function(msg){
var keyupCanceler = function(ev){
ev.stopPropagation();
return false;
};
document.addEventListener("keyup", keyupCanceler, true);
var retVal = _confirm(msg);
setTimeout(function(){
document.removeEventListener("keyup", keyupCanceler, true);
}, 150); // Giving enough time to fire event
return retVal;
};
})(window);
}
以上代码将通过捕获阶段禁止任何 keyup 事件到达 DOM 元素。
请检查这个更新的 jsFiddle:http://jsfiddle.net/mTrPQ/2/
关于javascript - Firefox:在确认弹出窗口时停止传播回车键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24366151/