我想点击按钮以外的地方,隐藏元素,但我不明白,我不知道该怎么做。
$(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/