图标无法通过 onclick 事件点击
icon not clickable with onclick event
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
简短回答:尝试使用 element.closest()
而不是 element.matches()
。
我怀疑这是你 if 语句中的条件。从外观上看,element.matches()
将 完全匹配 提供的 ID - 即,如果单击的元素具有该 ID,它将匹配,但如果单击没有明确具有 ID 的子元素,即使父元素具有 ID。
根据 Mozilla web docs,element.closest()
还应该匹配其父项与提供的条件匹配的任何元素,即使该元素本身不匹配。
请记住,这将更改返回值的类型 - matches()
returns 布尔值,而 closest()
returns 'closest' 元素匹配条件。
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
简短回答:尝试使用 element.closest()
而不是 element.matches()
。
我怀疑这是你 if 语句中的条件。从外观上看,element.matches()
将 完全匹配 提供的 ID - 即,如果单击的元素具有该 ID,它将匹配,但如果单击没有明确具有 ID 的子元素,即使父元素具有 ID。
根据 Mozilla web docs,element.closest()
还应该匹配其父项与提供的条件匹配的任何元素,即使该元素本身不匹配。
请记住,这将更改返回值的类型 - matches()
returns 布尔值,而 closest()
returns 'closest' 元素匹配条件。