使用 jQuery 检查文本框焦点

Check textbox focus using jQuery

本文关键字:焦点 文本 检查 jQuery 使用      更新时间:2023-09-26

可能的重复项:
使用 jQuery 测试输入是否具有焦点

我需要检查特定文本框是否具有焦点或不使用jQuery。所以我的代码是这样的,但它不起作用:

if (document.getElementById("lastname").focus = true) {
    alert("hello");
}

我的用例是这样的:我有一个文本框,当#lastname文本框获得或失去焦点时,应该显示或隐藏该文本框。但是,如果#lastname文本框失去另一个文本框的焦点,则后者应保持可见,直到它也失去焦点。

任何帮助将不胜感激。

if ($("#lastname").is(':focus')) {
    alert("hello");
}

jQuery Docs for :focus
jQuery Docs for .is()

<小时 />更新:要在字段获得/失去焦点时显示/隐藏元素,请使用focusinfocusout事件处理程序:

$(document).ready(function() {
    $('#lastname').focusin(function() {
        $(hidden-element).show();
    }).add(hidden-element).focusout(function() {
        if ( !$(hidden-element).is(':focus') ) {
            $(hidden-element).hide();
        }
    });
});
//where hidden-element is a reference to or selector for your hidden text field
$("#lastname").focus(function(){
    alert("lastname has focus");
});
if (document.getElementById("lastname").focus == true) {
        alert("hello");
    }

检查 == ,使用 = 是赋值

你可以试试jQuery的:focus选择器。或者,您始终可以添加一个类并检查该类。

试试这个

var status = $('#lastname').is(":focus");
alert(status);//false or true
<script type="text/javascript" language="javascript">
    function check() {
        if ($(document.activeElement).attr("id") === "element_name") {
            alert('checkbox is focused');
        }
    }
</script>