我正在研究模态,我想使模态叠加层在单击背景时消失。
function dismissModal() {
document.getElementById("modal").classList.remove("modal-overlay");
}
.modal-overlay {
background-color: rgba(0, 0, 0, .5);
bottom: 0;
display: block;
left: 0;
overflow: hidden;
position: fixed;
right: 0;
top: 0;
z-index: 1;
}
.modal-content {
background-color: #fff;
height: 20em;
width: 20em;
margin: auto;
}
<section id="modal" class="modal-overlay" onclick="dismissModal()">
<div class="modal-content">
<h1>Example Code</h1>
</div>
</section>
使用div或具有onClick属性的部分对语义来说不是很好,但是我不想将整个模式部分包装在按钮或锚标记中。
在这种用例中,人们通常会如何避免在div或section类中使用onClick?
答案 0 :(得分:0)
element.addEventListener(‘click’, event => /* Do stuff, hide modal */ )
使用React / JSX:
const handler = event => /* Do stuff, hide modal */
const buttonComponent = <button onClick={handler} />
答案 1 :(得分:0)
希望下面的代码段有所帮助。
function dismissModal() {
document.getElementById("modal").classList.toggle("modal-overlay");
document.getElementById("modal").classList.toggle("modal-hidden");
}
.modal-overlay {
background-color: rgba(0, 0, 0, .5);
bottom: 0;
display: block;
left: 0;
overflow: hidden;
position: fixed;
right: 0;
top: 0;
z-index: 1;
}
.modal-content {
background-color: #fff;
height: 20em;
width: 20em;
margin: auto;
}
.modal-hidden{
display:none;
}
<section id="modal" class="modal-overlay" onclick="dismissModal()">
<div class="modal-content">
<h1>Example Code</h1>
</div>
</section>
<button onclick="dismissModal()">Show Modal</button>