gpt4 book ai didi

javascript - window.onclick = function(event) 仅适用于第一项

转载 作者:行者123 更新时间:2023-12-03 22:44:52 28 4
gpt4 key购买 nike

Here is a jsfiddle of my complete code, where you can test the functionality of the two modals. Clicking outside the second modal closes it, while clicking outside the first modal does not close it.

我在 HTML 页面上有两个模态弹出窗口,打开它们后,可以通过使用以下代码在模态外部单击来关闭它们:

// When user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}

出于某种原因,此代码仅适用于我的 script.js 文件中的第二个(最后一个)实例。您可以看到,这个文件中实际上只有两段代码:第一个控制第一个模态,第二个控制第二个模态。上面代码的每个实例都位于 block 的末尾。
// Get modalCompanies
var modalCompanies = document.getElementById('companiesModal');

// Get button that opens the modalCompanies
var btnCompanies = document.getElementById("companiesOpen");

// Get <spanCompanies> element that closes the modalCompanies
var spanCompanies = document.getElementsByClassName("close")[0];

// When user clicks on the button, open the modalCompanies
btnCompanies.onclick = function() {
modalCompanies.style.display = "block";
}

// When user clicks on <spanCompanies> (x), close modalCompanies
spanCompanies.onclick = function() {
modalCompanies.style.display = "none";
}

// When user clicks anywhere outside of the modalCompanies, close it
window.onclick = function(event) {
if (event.target == modalCompanies) {
modalCompanies.style.display = "none";
}
}



// Get modalPrivacy
var modalPrivacy = document.getElementById('privacyModal');

// Get button that opens the modalPrivacy
var btnPrivacy = document.getElementById("privacyOpen");

// Get <spanPrivacy> element that closes the modalPrivacy
var spanPrivacy = document.getElementsByClassName("close")[1];

// When user clicks on the button, open the modalPrivacy
btnPrivacy.onclick = function() {
modalPrivacy.style.display = "block";
}

// When user clicks on <spanPrivacy> (x), close modalPrivacy
spanPrivacy.onclick = function() {
modalPrivacy.style.display = "none";
}

// When user clicks anywhere outside of the modalPrivacy, close it
window.onclick = function(event) {
if (event.target == modalPrivacy) {
modalPrivacy.style.display = "none";
}
}

是什么阻止了 window.onclick = function(event) { }在每个 block 的末尾都可以在两个 block 中起作用?

最佳答案

利用

window.addEventListener("click", function(event) {
});

代替
window.onclick = function() {
}

https://jsfiddle.net/qsL76mx6/

关于javascript - window.onclick = function(event) 仅适用于第一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45393553/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com