当用户在DIV之外单击时,使用jQuery隐藏DIV

HTML

达蒙Near

2020-03-16

我正在使用此代码:

$('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中有链接,当单击它们时它们不再起作用。

第1754篇《当用户在DIV之外单击时,使用jQuery隐藏DIV》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

6个回答
蛋蛋梅古一 2020.03.16

Copied from https://sdtuts.com/click-on-not-specified-element/

Live demo http://demos.sdtuts.com/click-on-specified-element

$(document).ready(function () {
    var is_specified_clicked;
    $(".specified_element").click(function () {
        is_specified_clicked = true;
        setTimeout(function () {
            is_specified_clicked = false;
        }, 200);
    })
    $("*").click(function () {
        if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
            $(".event_result").text("you were clicked on specified element");
        } else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
            $(".event_result").text("you were clicked not on specified element");
        }
    })
})
路易阿飞 2020.03.16

var exclude_div = $("#ExcludedDiv");;  
$(document).click(function(e){
   if( !exclude_div.is( e.target ) )  // if target div is not the one you want to exclude then add the class hidden
        $(".myDiv1").addClass("hidden");  

}); 

FIDDLE

卡卡西理查德 2020.03.16
var n = 0;
$("#container").mouseenter(function() {
n = 0;

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

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});
伽罗十三 2020.03.16

Even sleaker:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});
前端LEYLEY 2020.03.16

您可能要检查为主体触发的click事件的目标,而不是依赖stopPropagation。

就像是:

$("body").click
(
  function(e)
  {
    if(e.target.className !== "form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

同样,主体元素可能不包括浏览器中显示的整个视觉空间。如果您发现点击没有注册,则可能需要为HTML元素添加点击处理程序。

番长猿 2020.03.16

现场演示

检查点击区域不在目标元素中还是其子元素中

$(document).click(function (e) {
    if ($(e.target).parents(".dropdown").length === 0) {
        $(".dropdown").hide();
    }
});

更新:

jQuery停止传播是最好的解决方案

现场演示

$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

$(".dropdown").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $(".dropdown").hide();
});

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android