停止由于按键而触发的模糊事件 [英] stop blur event from triggering as a result of keypress
问题描述
当检测到事件"keydown"时,也会自动触发事件"blur".如果触发了"keydown"事件,如何防止元素上的"blur"事件发生? 这是 jsFiddle 和代码: HTML:
When the event 'keydown' is detected, the event 'blur' is also automatically triggered. How can I prevent the 'blur' event on the element if 'keydown' event is triggered? Here is the jsFiddle and the code: HTML:
<div id="delegatee">
<span id="ctrl" contenteditable="true"></span>
</div>
CSS:
#ctrl {
width:100px;
height:50x;
border:1px solid black;
display:inline-block;
}
JavaScript:
JavaScript:
function saveOrDelete() {
$("#ctrl").attr('contentEditable', false);
alert('Triggered'); // alerts 2 times
}
$("#delegatee").on('keydown blur', '#ctrl', saveOrDelete)
请注意,该解决方案无效:
Please note, that this solution doesn't work:
function saveOrDelete() {
$("#delegatee").off('keydown blur', '#ctrl', saveOrDelete)
$("#ctrl").attr('contentEditable', false);
alert('Trigger');
$("#delegatee").on('keydown blur', '#ctrl', saveOrDelete)
}
推荐答案
此行导致此行为:
$("#ctrl").attr('contentEditable', false);
跨度不再为contentEditable
时,它将失去焦点,因此会升高blur
.
As soon as the span is no longer contentEditable
it will lose focus and hence blur
is raised.
您将不得不重新考虑您的逻辑.
You will have to re-think your logic.
编辑(发表评论后):
由于上述原因,为了捕获紧随keydown
的blur
,您可以更改逻辑以首先检查跨度是否可编辑,然后根据该值采取措施.
In order to trap the blur
which immediately follows a keydown
because of the above reason, you may change your logic to first check if the span is editable and then take action based on that.
例如
var mode = $("#ctrl").prop('contentEditable');
if (mode == 'true') {
$("#ctrl").prop('contentEditable', false);
// your other processes here
} else {
return false;
}
检查您的提琴上的更新: http://jsfiddle.net/CxFaq/1/
Check the update on your fiddle: http://jsfiddle.net/CxFaq/1/
这篇关于停止由于按键而触发的模糊事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!