我正在使用这段代码:

$('body').click(function() {
   $('.form_wrapper').hide();
});

$('.form_wrapper').click(function(event){
   event.stopPropagation();
});

这个HTML:

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

问题是,我有链接在div和当他们不再工作时,点击。


当前回答

在弹出窗口中使用接受的答案时,可能会遇到一些问题。在某些情况下,点击一个随机位置可能会导致不必要的操作,即错误地单击一个按钮可能会将您带到一个新页面。

我不确定这是否是最有效的解决方案,但为了防止这种情况,我建议使用屏幕掩码。确保屏幕掩码位于<body>标签的正下方,这样它就可以覆盖所有的屏幕宽度:100%;高度:100%。还要注意,它的z-index: 99高于所有元素。如果你想让另一个项目或div在屏幕掩码激活时可点击,只需为该项目或div分配更高的z-index。

屏幕掩码最初是不显示的(display:none),当单击(onclick="hidemenu()")时,它调用一个hide函数。

<body>
<div class="screenmask" onclick="hidemenu()" style="position:fixed; width: 100%; height: 100%; top: 0px; right: 0px; display: none; z-index: 99;"></div>

处理“同一页面上多个不同弹出菜单”的javascript函数可能如下所示:

<script>
// an element with onclick="showmenu('id_here')" pops a menu in the screen
function showmenu(id) {  
  var popmenu = document.getElementById(id); // assume popmenu is of class .cardmenu
  $('.cardmenu').hide();   // clear the screen from other popmenus first
  $(popmenu).show();          // pop the desired specific menu
  $('.screenmask').show(); // activate screenmask
}
    
function hidemenu() {      // called when clicked on the screenmask
  $('.cardmenu').hide();   // clear the screen from all the popmenus
  $('.screenmask').hide(); // deactivate screenmask
}
</script>

其他回答

遇到同样的问题,就想出了这个简单的解决方法。它甚至可以递归工作:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

    // if the target of the click isn't the container nor a descendant of the container
    if (!container.is(e.target) && container.has(e.target).length === 0) 
    {
        container.hide();
    }
});

这么多答案,加一个肯定是一种通行权… 我没有看到当前(jQuery 3.1.1)的答案-所以:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
dojo.query(document.body).connect('mouseup',function (e)
{
    var obj = dojo.position(dojo.query('div#divselector')[0]);
    if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
        MyDive.Hide(id);
    }
});

你最好这样写:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});