Javascript 是否可以使用 JS 或 jQuery 为 DIV 编写 onFocus/lostFocus 处理程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11280379/
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-24 05:16:20  来源:igfitidea点击:

Is it possible to write onFocus/lostFocus handler for a DIV using JS or jQuery?

javascriptjqueryonfocuslost-focus

提问by phoenix

I have a div and when the user clicks the div a function should be called. And when the user clicks something else (anything other than this div) another function should be called.

我有一个 div,当用户单击 div 时,应该调用一个函数。并且当用户单击其他内容(除此 div 之外的任何内容)时,应调用另一个函数。

So basically i need to have onFocus() and lostFocus() function calls associated with this DIV. Is it available in JavaScript or even in jQuery?

所以基本上我需要有与这个 DIV 关联的 onFocus() 和 lostFocus() 函数调用。它在 JavaScript 甚至 jQuery 中可用吗?

Thanks.

谢谢。

回答by Mohammad Adil

You need to add tabindexattribute to div:

您需要将tabindex属性添加到div

$("#mydiv").focusin(function() {
  $("#mydiv").css("background", "red");
});
$("#mydiv").focusout(function() {
  $("#mydiv").css("background", "white");
});
#mydiv {
  width: 50px;
  height: 50px;
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv" tabindex="100"></div>
<div id="anotherdiv"></div>

回答by Tats_innit

Focus do not work on DIV: http://api.jquery.com/focus/

焦点不适用于DIVhttp: //api.jquery.com/focus/

ALso good read: jquery : focus to div is not working

还不错的阅读:jquery : focus to div is not working

If you want to focus a div or anything normally can't be focused, set the tag's tabindex to -1 first.
eg: $("div#header").attr("tabindex",-1).focus();

回答by Uncle

Not sure if this solution suits your web page, but you could use JQuery on() to attach a click event to the body element and delegate it to child div's. Then in your event handler, test the id attribute and handle as such; something like:

不确定此解决方案是否适合您的网页,但您可以使用 JQuery on() 将点击事件附加到 body 元素并将其委托给子 div。然后在您的事件处理程序中,测试 id 属性并按原样处理;就像是:

$(body).on("click", "div", function (evt) {
     if ($(this).attr("id") == "innerDiv") {
            handle inner div click here
     } else {
            hanlde out div click here
     {
}

Hope this helps...

希望这可以帮助...

回答by Pixel

Sure.

当然。

$("#your-div-id").focusin(function() {
    // code here
});

$("#your-div-id").focusout(function() {
    // code here
});