js實現點擊按鈕時顯示彈框,點擊按鈕及彈框之外的區域時隱藏彈框

轉自https://blog.csdn.net/yimawujiang/article/details/86496936css

問題:js實現點擊按鈕時顯示彈框,點擊按鈕及彈框之外的區域時隱藏彈框?ide

方案一:這個問題一般的辦法是使用阻止事件冒泡來實現,代碼以下(省略css):spa

<body>
<button id="btn1" onclick="alertBoxFn();stopBubble()">打開彈窗</button>
<div id="alertBox" onclick="stopBubble()"></div>
</body>
<script>
function alertBoxFn(e) {
alertBox.style.display = "block";
}
function stopBubble(e){
var e=e||window.event;
e.stopPropagation()
}
document.body.addEventListener('click', function() {
alertBox.style.display = 'none'
})
</script>

 

但這有一個弊端,就是若是頁面上須要有多個按鈕分別控制多個彈框,需求是點擊按鈕1時顯示彈框1,點擊按鈕2時顯示彈框2,同時隱藏彈框1。但結果倒是點擊按鈕2時,按鈕1並不會隱藏。這是由於按鈕2阻止了點擊事件的冒泡,致使body元素的點擊事件並無被觸發。因而,這裏咱們不能再使用阻止事件冒泡的方法了。.net

方案二:聲明一個變量用來判斷鼠標是否點擊的是按鈕或彈框。代碼以下(省略css):code

<body>
<button id="btn" onclick="alertBoxFn()">打開彈窗</button>
<div id="alertBox" onclick="outside=false"></div>
</body>


<script>
var outside=true
function alertBoxFn(e) {
outside=false
alertBox.style.display = "block";
}

//如下兩個方法用於判斷是點擊按鈕和彈框,仍是彈框外面,若是點擊彈框外面隱藏彈框,注document.body必需要在文檔後面寫,在head寫documnet.body爲null document.body.addEventListener(
'click', function() { outside=true },true) document.body.addEventListener('click', function() { if(outside){ alertBox.style.display = 'none' } }) </script>
相關文章
相關標籤/搜索