点弹窗之外,隐藏弹窗,或点击div之外,隐藏div
其实原理总结就两句话:
- 给整个document添加监听点击事件,隐藏div
- 给div添加监听点击事件,阻止冒泡
代码实现
html代码
<body><!-- 要隐藏的div --><div id="showDiv"></div>
</body>
js代码
const bt = document.getElementById('showButton');
const div = document.getElementById('showDiv');bt.addEventListener('click',function(event){div.style.display = 'block';event.stopPropagation();//阻止冒泡
})document.addEventListener('click',function(){div.style.display = 'none';//隐藏
});div.addEventListener('click',function(event){event.stopPropagation();//阻止冒泡
})
实现效果
完整代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>#showDiv{display: none;margin-top: 10px;height: 300px;width: 300px;background-color: aqua;border: 1px solid;}</style>
</head>
<body><button id="showButton">显示div</button><!-- 要隐藏的div --><div id="showDiv"></div><script>const bt = document.getElementById('showButton');const div = document.getElementById('showDiv');bt.addEventListener('click',function(event){div.style.display = 'block';event.stopPropagation();//阻止冒泡})document.addEventListener('click',function(){div.style.display = 'none';//隐藏});div.addEventListener('click',function(event){event.stopPropagation();//阻止冒泡})</script>
</body>
</html>
希望能帮助到大家,如果你也想和我一起学习前端,可查看个人首页其他文章,文章会不定期更新,关注我,让我们一起学习前端吧。