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

前端 未结 4 1203
滥情空心
滥情空心 2020-12-10 05:55

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

相关标签:
4条回答
  • 2020-12-10 06:02

    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();
    
    0 讨论(0)
  • 2020-12-10 06:05

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

    0 讨论(0)
  • 2020-12-10 06:20

    Sure.

    $("#your-div-id").focusin(function() {
        // code here
    });
    
    $("#your-div-id").focusout(function() {
        // code here
    });
    
    0 讨论(0)
  • 2020-12-10 06:24

    You need to add tabindex attribute to 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>

    0 讨论(0)
提交回复
热议问题