1 回答
TA贡献1946条经验 获得超3个赞
干得好:
getElementsByClassName行为不同于getElementById. getElementsByClassName:这将返回具有指定类名的元素子元素的集合,作为 NodeList 对象。
var modal = document.getElementsByClassName('modal')[0];
var btn = document.getElementsByClassName('open-modal')[0];
var close = modal.getElementsByClassName('close')[0];
btn.onclick = function() {
modal.style.display = 'block';
};
close.onclick = function() {
modal.style.display = 'none';
};
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
};
.modal {
display: none;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
background: rgba(0, 0, 0, 0.8);
z-index: 99999;
animation-name: show;
animation-duration: 0.5s
}
.modal-content {
position: relative;
background-color: #fff;
margin: 10% auto;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
}
@keyframes show {
0% {
display: none;
opacity: 0;
}
100% {
display: block;
opacity: 1;
}
}
.modal-header {
padding: 12px;
background-color: grey;
color: white;
}
.modal-body {
padding: 12px;
}
.modal-footer {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 12px;
}
.close {
color: #aaa;
float: right;
font-size: 16px;
}
.close:hover,
.close:focus {
color: black;
cursor: pointer;
}
<button class="open-modal" name="open-modal-btn">Open Modal</button>
<div class="modal demo-modal">
<div class="modal-content">
<div class="modal-header">
<span class='close'>X</span>
<h2>Modal Header</h2>
</div>
<div class="modal-body">
<p>Some text in the Modal Body</p>
<p>Some other text...</p>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
添加回答
举报