我正在使用这段代码:

$('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和当他们不再工作时,点击。


当前回答

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

其他回答

$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});
var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

var $container = $("#popup_container"); $container.click(function(e) { if (e.target.id == $container.attr("id")) { $(this).hide(); } }); #popup_container { background: rgba(200,200,200,0.6); width: 100vh; height: 100vh; position: fixed; display: flex; justify-content: center; align-items: center; } #popup { background: yellow; border: 1px solid black; position: absolute; width: 50%; height: 50%; display: flex; justify-content: center; align-items: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="popup_container"> <div id="popup"> Popup </div> </div>

https://jsfiddle.net/041pj7re/

根据文档,.blur()不仅仅适用于<input>标记。例如:

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

通过使用这段代码,您可以隐藏尽可能多的项目

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})