我“做”了一个模型(从here得到)。然而,关闭模式的按钮就是不起作用。不过,单击模式的任何部分以关闭它的事件确实有效。我已经在这上面花了几个小时,并尽可能地研究了很多,但我似乎就是找不到问题所在。
const modal = document.querySelector(".modal");
const closeModal = document.querySelector(".closeModal");
document.querySelector("#shortCircuit").onclick = function() {
modal.setAttribute('style', 'display: block;');
}
closeModal.onclick = function() {
modal.setAttribute('style', 'display: none;');
}
window.onclick = function(event) {
if (event.target === modal) {
modal.setAttribute('style', 'display: none;');
}
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: hsl(0, 0%, 0%);
background-color: hsla(0, 0%, 0%, 0.4);
}
.modal-content {
background-color: hsl(0, 0%, 100%);
margin: 15% auto;
padding: 20px;
border: 1px solid #878787;
width: 80%;
}
.closeModal {
color: #aaa;
float: right;
font-size: 2em;
font-weight: bold;
}
.closeModal:hover,
.closeModal:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div class="flexLayout">
<div id="shortCircuit">
<h1>Short-circuit</h1>
<div class="modal">
<div class="modal-content">
<button class="closeModal">×</button>
</div>
</div>
</div>
</div>
发布于 2018-12-06 04:09:54
问题是,单击X会使DOM向上冒泡,并再次触发<div id="shortCircuit">
上的开放模式代码。你可以用e.stopPropagation();
来阻止它
const modal = document.querySelector(".modal");
const closeModal = document.querySelector(".closeModal");
document.querySelector("#shortCircuit").onclick = function() {
modal.setAttribute('style', 'display: block;');
}
closeModal.onclick = function(e) {
e.stopPropagation();
modal.setAttribute('style', 'display: none;');
}
window.onclick = function(event) {
if (event.target === modal) {
modal.setAttribute('style', 'display: none;');
}
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: hsl(0, 0%, 0%);
background-color: hsla(0, 0%, 0%, 0.4);
}
.modal-content {
background-color: hsl(0, 0%, 100%);
margin: 15% auto;
padding: 20px;
border: 1px solid #878787;
width: 80%;
}
.closeModal {
color: #aaa;
float: right;
font-size: 2em;
font-weight: bold;
}
.closeModal:hover,
.closeModal:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
<div class="flexLayout">
<div id="shortCircuit">
<h1>Short-circuit</h1>
<div class="modal">
<div class="modal-content">
<button class="closeModal">×</button>
</div>
</div>
</div>
</div>
发布于 2018-12-06 04:18:39
代码的问题在于它关闭了对话框,然后触发了显示对话框事件。这是因为单击事件会在鼠标下方的每一层中冒泡。要停止此操作,只需将代码更改为以下代码
closeModal.onclick = function(e) {
modal.setAttribute('style', 'display: none;');
e.preventDefault();
e.stopPropagation();
}
https://stackoverflow.com/questions/53639885
复制相似问题