How to blur the div element?

不打扰是莪最后的温柔 提交于 2019-11-26 04:51:35

问题


I have a dropdown menu inside a DIV.

I want the dropdown to be hide when user click anywhere else.

$(\'div\').blur(function() { $(this).hide(); }

is not working.

I know .blur works only with <a> but in this case what is the simplest solution?


回答1:


I think the issue is that divs don't fire the onfocusout event. You'll need to capture click events on the body and then work out if the target was then menu div. If it wasn't, then the user has clicked elsewhere and the div needs to be hidden.

<head>
  <script>
  $(document).ready(function(){
    $("body").click(function(e) {
      if(e.target.id !== 'menu'){
        $("#menu").hide();
      }      
    });
  });
  </script>
  <style>#menu { display: none; }</style>
</head>

<body>
  <div id="menu_button" onclick="$('#menu').show();">Menu....</div>
  <div id="menu"> <!-- Menu options here --> </div>

  <p>Other stuff</p>
</body>



回答2:


Try using tabindex attribute on your div, see:

Check this post for more information and demo.




回答3:


$("body").click(function (evt) {
     var target = evt.target;
     if(target.id !== 'menuContainer'){
            $(".menu").hide();
    }                
});

give the div an id, for instance "menuContainer". then you can check by target.id instead of target.tagName to make sure its that specific div.




回答4:


Not the cleanest way, but instead of capturing every click event on the page you could add an empty link to your div and use it as a "focus proxy" for the div.

So your markup will change to:

<div><a id="focus_proxy" href="#"></a></div>

and your Javascript code should hook to the blur event on the link:

$('div > #focus_proxy').blur(function() { $('div').hide() })

Don't forget to set the focus on the link when you show the div:

$('div > #focus_proxy').focus()



回答5:


I just encountered this problem. I guess none of the above can fix the problem properly, so I post my answer here. It's a combination of some of the above answers: at least it fixed 2 problems that one might met by just check if the clicked point is the same "id"

$("body").click(function(e) {
    var x = e.target;

    //check if the clicked point is the trigger
    if($(x).attr("class") == "floatLink"){
        $(".menu").show();
    } 
    //check if the clicked point is the children of the div you want to show 
    else if($(x).closest(".menu").length <= 0){
       $(".menu").hide();
    }
});



回答6:


.click will work just fine inside the div tag. Just make sure you're not over top of the select element.

$('div').click(function(e) {
    var $target = $(e.target);
    if (!$target.is("select")) { $(this).hide() };
});


来源:https://stackoverflow.com/questions/1259716/how-to-blur-the-div-element

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