【发布时间】:2012-07-01 22:35:52
【问题描述】:
使用 jQuery,如何获取具有插入符号(光标)焦点的输入元素?
或者换句话说,如何确定输入是否具有插入符号的焦点?
【问题讨论】:
标签: javascript jquery element caret
使用 jQuery,如何获取具有插入符号(光标)焦点的输入元素?
或者换句话说,如何确定输入是否具有插入符号的焦点?
【问题讨论】:
标签: javascript jquery element caret
// Get the focused element:
var $focused = $(':focus');
// No jQuery:
var focused = document.activeElement;
// Does the element have focus:
var hasFocus = $('foo').is(':focus');
// No jQuery:
elem === elem.ownerDocument.activeElement;
你应该使用哪一个?引用jQuery docs:
与其他伪类选择器(以“:”开头的选择器)一样,建议在 :focus 前面加上标签名称或其他选择器;否则,隐含通用选择器(“*”)。换句话说,裸露的
$(':focus')等价于$('*:focus')。如果您正在寻找当前聚焦的元素,$( document.activeElement ) 将检索它而无需搜索整个 DOM 树。
答案是:
document.activeElement
如果你想要一个包裹元素的 jQuery 对象:
$(document.activeElement)
【讨论】:
$focused 的方式,因为我假设你这样做是为了表示 var 是一个 jquery 对象。 TYVM。
$( document.activeElement )
无需按照jQuery documentation 的建议搜索整个 DOM 树即可检索它
【讨论】:
我在 Firefox、Chrome、IE9 和 Safari 中测试了两种方式。
(1)。 $(document.activeElement) 在 Firefox、Chrome 和 Safari 中按预期工作。
(2)。 $(':focus') 在 Firefox 和 Safari 中按预期工作。
我移动到鼠标中输入“名称”并在键盘上按 Enter,然后我尝试获取焦点元素。
(1)。 $(document.activeElement) 在 Firefox、Chrome 和 Safari 中按预期返回 input:text:name,但在 IE9 中返回 input:submit:addPassword
(2)。 $(':focus') 在 Firefox 和 Safari 中按预期返回 input:text:name,但在 IE 中没有任何内容
<form action="">
<div id="block-1" class="border">
<h4>block-1</h4>
<input type="text" value="enter name here" name="name"/>
<input type="button" value="Add name" name="addName"/>
</div>
<div id="block-2" class="border">
<h4>block-2</h4>
<input type="text" value="enter password here" name="password"/>
<input type="submit" value="Add password" name="addPassword"/>
</div>
</form>
【讨论】:
试试这个:
$(":focus").each(function() {
alert("Focused Elem_id = "+ this.id );
});
【讨论】:
.each非承受)
怎么没人提..
document.activeElement.id
我用的是IE8,还没有在其他浏览器上测试过。在我的例子中,我使用它来确保一个字段至少有 4 个字符并且在行动之前集中注意力。一旦你输入第四个数字,它就会触发。该字段的 id 为“年份”。我正在使用..
if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
// action here
}
【讨论】:
$(':focus')[0] 会给你实际的元素。
$(':focus') 将为您提供一组元素,通常一次只关注一个元素,因此只有以某种方式关注多个元素时才会更好。
【讨论】:
试试这个::
$(document).on("click",function(){
alert(event.target);
});
【讨论】:
如果你想确认焦点是否在一个元素上,那么
if ($('#inputId').is(':focus')) {
//your code
}
【讨论】: