<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#test{
position: fixed;
height: calc(100vh - 20px);
width: 400px;
padding: 15px;
top:20px;
right: -400px;
background: skyblue;
transition: right .3s linear;
}
#test.show{
right: 0px;
}
#close{
display: inline-block;
padding: 6px;
cursor: pointer;
}
</style>
</head>
<body>
<button class="btn">我是一个按钮,我要显示隐藏的div</button>
<div id="test" class="">
<div class="title">
<span id="close">×</span>
</div>
<div class="content">
<input type="text">
<input type="text">
<select name="" id=""></select>
div测试内容,点击除了按钮的其它地方会隐藏此div模块。
</div>
<div class="">
<button id="save" >我是一个按钮,我要保存</button>
</div>
</div>
<script type="text/javascript">
document.querySelector(".btn").onclick = function(e){
window.event? window.event.cancelBubble = true : e.stopPropagation();//阻止冒泡,不进入document的click的回调
document.getElementById("test").classList.add("show");
};
document.querySelector("#close").onclick = function(e){
window.event? window.event.cancelBubble = true : e.stopPropagation();//阻止冒泡,不进入document的click的回调
document.getElementById("test").classList.remove("show");
};
document.querySelector("#save").onclick = function(e){
window.event? window.event.cancelBubble = true : e.stopPropagation();//阻止冒泡,不进入document的click的回调
document.getElementById("test").classList.remove("show");
};
document.onclick = function(e){
var e = e || window.event; //浏览器兼容性
var elem = e.target || e.srcElement;
console.log(elem.getAttribute('class'))
// if(elem.getAttribute('class')=="btn"){//因为按钮的点击事件已经阻止冒泡了,所以这段代码注释掉; 如果没有阻止冒泡的话,注释要放开
// return;
// }
while (elem) { //循环判断至跟节点,防止点击的是div#test子元素
if (elem.id && elem.id == 'test') {
return;
}
elem = elem.parentNode;
}
document.getElementById("test").classList.remove("show")
}
</script>
</body>
点击页面任何地方,将div隐藏,除了指定位置外 (原生js)
于 2019-06-11 11:12:41 首次发布