我正在使用 jquery-ui 模态,我的应用程序使用几个绑定(bind)到模态对话框的热键。
这是我的工作 jsfiddle example和代码:
$(document).keypress(function(e){console.log("pressed a key: " + e.which);})
var dialog = $('#modal-dialog')
.dialog({ modal: true, autoOpen: false, buttons: [{text:"ok"}] });
.keypress(function(e){console.log("cought!"); e.stopPropagation()})
$("#bt").click(function(){dialog.dialog("open")})
当模式对话框打开时,它应该抑制按键事件从 Dom 树向上传输到文档/窗口。 当输入元素具有焦点(不适用于按钮)时,stopPropagation 就会启动。 否则,事件将被传播。
解决这个问题的最佳方法是什么?
最佳答案
当对话框打开时,您可以取消绑定(bind)
$(document).keypress
事件,然后再次绑定(bind)
$(document).keypress
当对话框关闭时。
这是DEMO
js代码:
function bind_event()
{
$(document).keypress(function(e){console.log("pressed a key: " + e.which);});
}
function unbind_event()
{
$(document).unbind('keypress');
}
$(document).ready(function(){
bind_event();
var dialog = $('#modal-dialog')
.dialog({
modal: true, autoOpen: false, buttons: [{text:"ok"}],
open: function( event, ui ) {
unbind_event();
/*$(document).keypress(function(e){
console.log('dialog open '+e.which);
});*/
},
close: function( event, ui ) {
bind_event();
}
})
.keypress(function(e){
console.log("cought!");
e.stopPropagation()
})
$("#bt").click(function(){dialog.dialog("open")});
});
关于jQuery UI 模式对话框 : Prevent keypressed when dialog is open,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24942336/