一、jq
<div class="small_img" style="width: 100px;height: 100px;border: 1px solid red;"></div>
<script>
$(document).click(function(e) {
var demo = $('.small_img');//目标区域
if (!demo.is(e.target) && demo.has(e.target).length == 0 ) {
// 排除了目标区域后,进行操作
$('.small_img').css("display", "none");
}
})
</script>
二、原生js
点击document内的所有DOM元素,都会冒泡到document.body上。阻止本身不冒泡即可。
<div id="small_img" style="width: 100px;height: 100px;border: 1px solid red;"></div>
<script>
let demo = document.getElementById("small_img");
document.body.onclick = function() {
demo.style.display = "none"
}
demo.onclick = function(event){
//兼容IE低版本
event.stopPropagation();
event.cancelBubble = true;
}
</script>