模态工作,直到重复



我有一个我创建的javascript模式,它工作正常,除非页面上有2个。当页面上存在其中的 2 个时,第一个将起作用,但下一个现在可以工作。

这是控制它的JS:

// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
trigger.onclick = function() {
modal.style.display = "block";
};
// Get the modal linked with with trigger element
let modal = document.getElementById(
trigger.href.substring(trigger.href.indexOf("#") + 1)
);
// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
allClose[i].onclick = function() {
modal.style.display = "none";
};
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
if (e.target == modal) {
modal.style.display = "none";
}
};

这是一个工作示例。我尝试过使用var而不是let,但不能 100% 确定如何以编程方式将它们范围限定为其特定的 html 结构。

您需要为每个模态使用唯一的 ID:

<div id="modal-1" class="m-modal">...</div>
<div id="modal-2" class="m-modal">...</div>

并为每个触发器设置触发器,而不仅仅是第一个触发器:

let triggers = [].slice.call(document.getElementsByClassName('js-modal'))
triggers.forEach(function(trigger) {
// ...
}

JSFiddle 演示:https://jsfiddle.net/eoy2erpp/1/

这是一个解决方案,很脏但有效 斯菲德尔

var trigger = document.getElementsByClassName("js-modal")[1];
trigger.onclick = function() {
modal.style.display = "block";
};
let trigger = document.getElementsByClassName("js-modal")[0];

你只绑定到js中的第一个按钮。没有什么与你的第二个绑定

更改你的 JavaScript:

// Get the button that opens the modal
let trigger = document.getElementsByClassName("js-modal")[0];
let trigger1 = document.getElementsByClassName("js-modal")[1];
trigger.onclick = function() {
modal.style.display = "block";
};
trigger1.onclick = function() {
modal.style.display = "block";
};
// Get the modal linked with with trigger element
let modal = document.getElementById(
trigger.href.substring(trigger.href.indexOf("#") + 1)
);
// When the user clicks the button, open the modal
let allClose = modal.getElementsByClassName("js-modal-close");

// All elments linked to the modal can close the modal
for (let i = 0; i < allClose.length; i++) {
allClose[i].onclick = function() {
modal.style.display = "none";
};
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(e) {
if (e.target == modal) {
modal.style.display = "none";
}
};

最新更新