首页 文章

如何使用jQuery获取焦点元素?

提问于
浏览
313

使用jQuery,我如何获得具有插入符号(光标)焦点的输入元素?

或者换句话说,如何确定输入是否具有插入符号的焦点?

7 回答

  • 1
    $( document.activeElement )
    

    将检索它,而不必按照jQuery documentation上的建议搜索整个DOM树

  • 0

    试试这个:

    $(":focus").each(function() {
        alert("Focused Elem_id = "+ this.id );
    });
    
  • 0
    // 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') . 如果您正在寻找当前关注的元素,$(document.activeElement)将检索它而无需搜索整个DOM树 .

    答案是:

    document.activeElement
    

    如果你想要一个包装元素的jQuery对象:

    $(document.activeElement)
    
  • 6

    我在Firefox,Chrome,IE9和Safari中测试了两种方法 .

    (1) . $(document.activeElement) 在Firefox,Chrome和Safari中按预期工作 .

    (2) . $(':focus') 在Firefox和Safari中按预期工作 .

    我移动鼠标输入'name'并在键盘上按Enter键,然后我尝试获得聚焦元素 .

    (1) . $(document.activeElement) 在Firefox,Chrome和Safari中返回输入:text:name,但它返回输入:在IE9中提交:addPassword

    (2) . $(':focus') 返回输入:text:Firefox和Safari中预期的名称,但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>
    
  • 32

    怎么没人提到..

    document.activeElement.id
    

    我正在使用IE8,并没有在任何其他浏览器上测试它 . 在我的情况下,我正在使用它来确保一个字段至少4个字符并在表演之前集中注意力 . 输入第4个数字后,它会触发 . 该字段的ID为“年份” . 我在用..

    if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
        // action here
    }
    
  • 5

    $(':focus')[0] 将为您提供实际元素 .

    $(':focus') 将为您提供一个元素数组,通常一次只关注一个元素,所以只有在您以某种方式聚焦多个元素时才会更好 .

  • 682

    试试这个::

    $(document).on("click",function(){
        alert(event.target);
        });
    

相关问题