我将此Modal用于我网站的一个页面上的多个链接。我需要的是一个脚本/代码,当用户点击外面时关闭模态窗口。我找到了这个post,但它只能用于一个链接,因为脚本需要id。有没有办法将此脚本应用于多个ID?还是其他方法?
答案 0 :(得分:1)
这是基于id
,因为它来自:target
,所以您需要做的是,为这样的不同模态提供一个公共类和不同的ID:
window.onload = function () {
var modals = document.getElementsByClassName("modal");
var windows = document.getElementsByClassName("window");
var clearModal = function () {
location.hash = '';
};
for (var i = 0; i < modals.length; i++) {
modals[i].addEventListener('click', clearModal, false);
}
for (var i = 0; i < windows.length; i++) {
windows[i].addEventListener('click', function () {
event.stopPropagation();
event.cancelBubble = true;
}, false);
}
document.body.addEventListener('keydown', function () {
if (event.keyCode == 27) {
location.hash = '';
clearModal();
}
}, false);
};
&#13;
* {
margin: 0;
padding: 0;
list-style: none;
}
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.25);
z-index: 9999;
pointer-events: none;
opacity: 0;
}
.modal .window {
background-color: #fff;
position: absolute;
top: 50%;
left: 50%;
width: 300px;
height: 200px;
margin: -100px 0 0 -150px;
text-align: center;
line-height: 120px;
}
.modal:target {
opacity: 1;
pointer-events: auto;
}
&#13;
<div id="modal-1" class="modal">
<div class="window">Modal Window 1<br /><a href="#">Close</a></div>
</div>
<div id="modal-2" class="modal">
<div class="window">Modal Window 2<br /><a href="#">Close</a></div>
</div>
<div id="modal-3" class="modal">
<div class="window">Modal Window 3<br /><a href="#">Close</a></div>
</div>
<div id="modal-4" class="modal">
<div class="window">Modal Window 4<br /><a href="#">Close</a></div>
</div>
<div id="modal-5" class="modal">
<div class="window">Modal Window 5<br /><a href="#">Close</a></div>
</div>
<a href="#modal-1">Open Modal 1</a><br />
<a href="#modal-2">Open Modal 2</a><br />
<a href="#modal-3">Open Modal 3</a><br />
<a href="#modal-4">Open Modal 4</a><br />
<a href="#modal-5">Open Modal 5</a>
&#13;