點擊盒子外任意位置關閉當前盒子

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
	   div{
	   	width: 500px;
	   	height: 500px;
	   	background: #ccc;
	   	margin:100px auto;
	   	display: none;
	   }
    </style>
</head>
<body>
	<button id="btn">點擊</button>
	<div id="box"></div>
</body>
</html>
<script>
    var btn=document.getElementById('btn');
    var box=document.getElementById('box');
    btn.onclick=function(e){
    	box.style.display='block';
    	window.event? window.event.cancelBubble = true : e.stopPropagation();//阻止事件向上冒泡
    }
    document.onclick=function(e){
        box.style.display='none';
    }
    box.onclick=function(e){
       window.event? window.event.cancelBubble = true : e.stopPropagation();//阻止事件向上冒泡
    }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章