我目前陷入困境,因为我似乎无法让 addEventListener 工作。
我已经尝试过开发。 addEventListener 上有断点的工具,但它们不会停止脚本,所以我猜检测 click
和 mouseleave
和 mouseenter< 的代码有问题
function hide() {
document.getElementById("links").style.display = "none";
};
function show() {
document.getElementById("links").style.display = "flex";
};
var menu = document.getElementById("menu");
menu.addEventListener("mouseenter", show);
menu.addEventListener("mouseleave", hide);
menu.addEventListener("click", show);
document.addEventListener("click", function() {
if (this != menu) {
document.getElementById("links").style.display = "none";
}
});
#menu {
height: 10vh;
background-color: red;
text-align: center;
transition: all 1s ease-out;
padding-top: 5vh;
}
#menu:hover {
color: red;
}
#envelope {
height: 0;
display: block;
background-color: blue;
min-width: 100%;
z-index: 1;
position: absolute;
left: 0;
content: "";
opacity: 0;
transition: all 1.3s ease-out;
}
#links {
height: 0;
display: none;
background-color: pink;
justify-content: center;
z-index: 2;
min-width: 100%;
opacity: 0;
transition: all 1s ease-in;
}
#google {
margin-top: -1vh;
width: 150px;
}
#mysite {
padding-left: 5%;
margin-top: -1vh;
width: 150px;
}
#menu:hover #links {
opacity: 1;
height: 100px;
}
#menu:focus #links {
opacity: 1;
height: 100px;
}
#menu:hover #envelope {
height: 100px;
opacity: 1;
}
#menu:focus #envelope {
height: 100px;
opacity: 1;
}
<div id="menu">Click here to browse the internet.
<div id="envelope">
<div id="links">
<div>
<a href="https://www.google.com"><img id="google" src="https://seomofo.com/wp-content/uploads/2010/05/google_logo_new.png" /></a>
</div>
<div style="width: 20%;"></div>
<div>
<a href="https://www.mywebsite.com/si/"><img id="mysite" src="https://toppng.com/uploads/preview/wwf-logo-horizontal-world-wildlife-foundation-logo-shirt-11563219164hg5hfcveei.png" /></a>
</div>
</div>
</div>
</div>
最佳答案
在您的代码片段中,addEventListener
正在工作,但看起来代码没有产生您想要或期望的行为。您似乎没有考虑事件通过 DOM 传播的方式。
您可以在这里阅读相关内容: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation
您可能想要如下所示的内容:
document.addEventListener("click", function (event) {
event.stopPropagation();
console.log("clicked", event.target, this);
if (event.target != menu) {
/* something else was clicked */
} else {
/* the menu was clicked */
}
});
请注意,单击处理程序正在命名一个名为“事件”的参数。然后我们使用 event.stopPropagation()
并查看 event.target
而不是 this
。
我还添加了 console.log
语句,以便您可以看到 this
关键字与 event.target
值之间的差异>.
关于javascript - 似乎无法让 addEventListener 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60395134/