js实现点击按钮出现元素,点击其他地方隐藏该元素
首先为控制出现消失的被点击元素添加点击事件,并且使用stopProp()函数防止该元素上的事件冒泡。然后给body添加点击事件,点击时需要消失的元素添加属性display: none;,这样变可以实现点击其他区域该元素消失。 注意几点:
初始display: none;属性需要设置成行内样式,否则会导致element.style.dispaly方法第一次获取不到值而需要点击两次才能看到效果。如果非要设置成外联样式,可以使用window.getComputedStyle(element, [pseudoElt]);方法获取。具体参考:MDN getComputedStyle方法stopPropagation()和cancelBubble()方法为阻止事件冒泡的方法,其中stopPropagation()符合W3C标准,适用于Chrome、Firefox等浏览器。cancelBubble不符合W3C标准,适用于IE浏览器。
body {
width: 100%;
height: 500px;
}
#outside {
width: 200px;
height: 50px;
background-color: aquamarine;
}
点击这里出现列表
window.onload = function () {
const outside = document.getElementById("outside");
outside.addEventListener("click", viewModal);
const body = document.getElementsByTagName("body")[0];
body.addEventListener("click", hideModal);
const modal = document.getElementById("modal");
// 防止点击 modal 列表时列表消失
modal.addEventListener("click", (e) => { stopProp(e); });
}
function viewModal (e) {
stopProp(e); // 防止事件冒泡导致触发body上绑定的点击事件
const modal = document.getElementById("modal");
const disp = modal.style.display;
modal.style.display = disp === "none" ? "block" : "none";
}
function hideModal () {
const o = document.getElementById("modal");
o.style.display = "none";
}
/**
* 阻止事件冒泡
*/
function stopProp (e) {
e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
}
参考: https://www.cnblogs.com/sghy/p/10044313.html https://blog.csdn.net/gmd_web/article/details/49661091