Javascript 使用 jQuery 检查文本框焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12016725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:54:27  来源:igfitidea点击:

Check textbox focus using jQuery

javascriptjquerytextboxfocus

提问by user853575

Possible Duplicate:
Using jQuery to test if an input has focus

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

I need to check if a particular textbox has the focus or not using jQuery. So my code is like this, but it is not working:

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

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

My use-case is this: I have a textbox which should be shown or hidden when the #lastnametextbox gains or loses focus. However, if the #lastnametextbox loses the focus to the other textbox, the latter should remain visible until it loses focus as well.

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

Any help will be appreciated.

任何帮助将不胜感激。

回答by nbrooks

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

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

jQuery 文档:focus
jQuery 文档.is()



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

$(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

回答by redDevil

$("#lastname").focus(function(){
    alert("lastname has focus");
});

回答by rowasc

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

Check with == , using = is an assignment

检查 == ,使用 = 是一个赋值

回答by gerky

You can try jQuery's :focusselector. Or you can always add a class and check for that class.

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

回答by Anant Dabhi

<script type="text/javascript" language="javascript">

    function check() {

        if ($(document.activeElement).attr("id") === "element_name") {
            alert('checkbox is focused');
        }
    }

</script>

回答by VBH

Try this

尝试这个

var status = $('#lastname').is(":focus");
alert(status);//false or true