我计划在单击空格键时执行一项操作。它确实发生了。
// when space bar is pressed
do-something; // Applied on the $(document).keypress..
但是,当我按空格键时,以及必须触发的事件/操作,模态加载/再次显示。为什么会这样呢?我试图阻止模态再次加载:
$('#goal').on('hidden.bs.modal',function() {
$(document).focus(); // Get the button that triggered modal
// out of focus
});
但是文档没有获得焦点,触发模态加载的按钮仍然处于焦点状态,直到我单击屏幕使文档重新获得焦点。如何防止模态在按空格键时再次加载?
我还尝试了触发模式的按钮上的 blur()
函数。但这没有帮助吗?
最佳答案
使用 $(document).focus();
不会有任何效果,因为 document
不是一个可聚焦的元素,它实际上根本不是一个元素。尝试使用 document.activeElement
获取事件元素并对其进行模糊
。
document.activeElement.blur();
为此,您需要在模式关闭时监听事件 hidden.bs.modal
,因为 Bootstrap 会在关闭时自动将焦点返回到按钮。
示例(Live):
$(document).on('hidden.bs.modal', function() {
document.activeElement.blur();
});
或者,您可以将焦点设置到模型本身中的可聚焦元素(如果存在)。这可能会带来最愉快的用户体验。
关于javascript - 为什么modal弹出按空格键会按?我该如何预防?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29030212/