How to blur the div element?

雨燕双飞 提交于 2019-11-26 16:37:43
djch

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>
Amar Palsapure

Try using tabindex attribute on your div, see:

Check this post for more information and demo.

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

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

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

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