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

痞子三分冷 提交于 2019-11-27 03:30:46

问题


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.

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

Thanks.


回答1:


Here i created a Working demo of what you want http://jsfiddle.net/kPbfL/1/

You need to add tabindex attribute to div :

Markup:

 <div id="mydiv" tabindex="-1"></div>

Javascript

$("#mydiv").focusin(function() {
  $("#mydiv").css("background","red");
});
$("#mydiv").focusout(function() {
  $("#mydiv").css("background","white");
});

CSS

#mydiv{
width : 50px;
    height:50px;
    border : 1px solid red;
}​
​



回答2:


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

ALso good read: 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();



回答3:


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:

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




回答4:


Sure.

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

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


来源:https://stackoverflow.com/questions/11280379/is-it-possible-to-write-onfocus-lostfocus-handler-for-a-div-using-js-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!