看看ContentEditable div是否有焦点 [英] See if ContentEditable div has focus
问题描述
我试图检查一个contenteditable div是否有焦点,但我有一些麻烦。这是我的代码到目前为止:
I'm attempting to check whether or not a contenteditable div has focus, but I'm having some trouble. Here's my code so far:
if ($("#journal-content:focus")) {
alert("Has Focus");
} else {
alert("Doesn't Have Focus");
}
问题是,它总是返回有焦点 t。
The problem is, it's always returning "Has focus" even when it doesn't. What's the best way to go about doing this?
更新:这样做的原因是看光标是否在所需位置 之前插入新元素。否则,如果用户单击的最后一个位置在标题中,那么当我使用Rangy还原选择并将其替换为新元素时,它将在标题中结束。我需要一个方法来确定contenteditable div是否集中/有光标在其中,如果没有,我将简单地追加我插入的元素在结尾。
Update: The reason for doing this is to see whether or not the cursor is in the desired location before inserting the new element. Otherwise, if the last place the user clicked was in the header, then when I restore the selection with Rangy and replace it with a new element, it ends up in the header. I need a way to find out if the contenteditable div is focused/has the cursor in it, so if not, I'll simply append the element I'm inserting at the end.
更新2:这是一个说明我的问题的JSFiddle: http://jsfiddle.net/2NHrM/
Update 2: Here's a JSFiddle illustrating my problem: http://jsfiddle.net/2NHrM/
推荐答案
尝试:
if ($("#journal-content").is(":focus")) {
alert("Has Focus");
} else {
alert("Doesn't Have Focus");
}
或:
window.contenteditable_focused = false;
$("#journal-content").focus(function() {
//alert("Has Focus");
contenteditable_focused = true;
});
$("#journal-content").blur(function() {
//alert("Doesn't Have Focus");
contenteditable_focused = false;
});
在执行脚本之前检查 contenteditable_focused
。
Check for contenteditable_focused
before executing your script.
或:
if ($( document.activeElement ).is("#journal-content")) {
alert("Has Focus");
} else {
alert("Doesn't Have Focus");
}
这篇关于看看ContentEditable div是否有焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!