能否使用JS或jQuery为一个DIV写onFocuslostFocus处理程序?

问题描述 投票:8回答:4

我有一个div,当用户点击这个div时,应该调用一个函数。当用户点击其他东西时(除了这个div之外的任何东西),另一个函数应该被调用。

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

谢谢。

javascript jquery onfocus lost-focus
4个回答
24
投票

你需要添加 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>

6
投票

重点不在工作上 DIV : http:/api.jquery.comfocus。

也好读。jquery:聚焦到div不工作了

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();

0
投票

不知道这个解决方案是否适合你的网页,但你可以使用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
     {
}

希望这能帮到你...


-1
投票

当然可以。

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

$("#your-div-id").focusout(function() {
    // code here
});
© www.soinside.com 2019 - 2024. All rights reserved.