onclick 事件仅适用于按钮。如果我单击按钮中的图标,则该功能不起作用。
enter code here
<div class="dropdown">
<button onclick="myFunction()" class="elementor-button-link elementor-button elementor-size-md elementor-animation-grow" id="dropbtn">
<script>/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('#dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
enter code here
答案 0 :(得分:0)
简短回答:尝试使用 dotenv
而不是 element.closest()
。
我怀疑这是您的 if 语句中的条件。从它的外观来看,element.matches()
将完全匹配所提供的 ID - 即,如果点击的元素具有该 ID,它将匹配,但如果您点击一个子元素,则不会匹配没有明确的 ID,即使父级有。
根据 Mozilla web docs,element.matches()
还应该匹配其父元素与提供的条件匹配的任何元素,即使元素本身不匹配。
请记住,这会改变返回值的类型 - element.closest()
返回一个布尔值,而 matches()
返回与条件匹配的“最近”元素。