javascript - 单击外部选择器触发事件

标签 javascript jquery

我想点击按钮以外的地方,隐藏元素,但我不明白,我不知道该怎么做。

$(function(){
  
  $(document).on('click','#foo',function(){
    let div = $('#bar');
    if( div.css('display') === 'none' ){
      div.show();
    }
    
    else{
      div.hide();
    }
  });

})
#foo{
  min-width: 35%;
}

#bar{
  max-width: 35%;
  min-height: 100px;
  background-color: aliceblue;
  border: 1px solid blue;
  border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="foo">Toggle</button><br><br>
<div id="bar"></div>

我有个想法,但行不通。

  $(document).on('click','html',function(e){
    if(e.eventTarget !== 'foo'){
      $('#bar').hide();
    }
  });

我遇到了 2 个问题,如果选择器是 html,页面将不会响应,而其中的代码只是为了显示我想要得到的内容。

最佳答案

不需要 jQuery,您可以简单地测试 .closest('#bar') 是否存在:

const bar = document.querySelector('#bar');
let hidden = false;
document.body.addEventListener('click', (e) => {
  if (e.target.closest('#foo')) {
    console.log('clicked inside, returning');
    return;
  }
  console.log('clicked outside');
  bar.style.display = hidden ? 'block' : 'none';
  hidden = !hidden;
});
body {
  height: 200px;
}
#foo{
  min-width: 35%;
}

#bar{
  max-width: 35%;
  min-height: 100px;
  background-color: aliceblue;
  border: 1px solid blue;
  border-radius: 5px;
}
<button id="foo">Toggle</button>
<div id="bar"></div>

关于javascript - 单击外部选择器触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50167065/

相关文章:

jquery - 在 Aurelia 应用程序中绑定(bind) FullCalendar 时超出最大调用堆栈大小

javascript - 使用 onclick 创建元素

javascript - val() 和 text() 的区别

javascript - 将 SQL 数组数据解析为 php mail()

javascript - 如何从 TypeScript 项目中调用 JavaScript 库?

javascript - 访问网站时如何查找浏览器发出的所有 JavaScript 请求

jquery - 如何在 jQuery 的 for 循环中向 href 添加变量?

asp.net-mvc - 如何删除 mvc 中带有选定选项标签的下拉菜单的模型状态错误?

for循环完成后Javascript不工作

javascript - 想要使用 document.getelementbyid 显示两个变量