本机Javascript点击事件无法处理按钮中的图标



我的HTML+Tailwindcss页面中有一个按钮,如下所示:

<div class="fixed bottom-4 right-4 z-10">
<button
id="button-fab-anchor"
class="z-50 whitespace-nowrap flex items-center px-3.5 py-2 rounded-full shadow-xl
outline-none focus:outline-none border-t border-b border-transparent
combo-primary hover:bg-primary-contrast active:bg-primary-contrast"
>
<span class="z-40 icon-inverse-primary text-lg text-center">
<i id="up-icon" class="fal fa-chevron-up"></i>
<i id="down-icon" class="fal fa-chevron-down hidden"></i>
</span>
</button>
<ul id="button-fab-list" class="absolute bottom-full right-0 flex flex-col justify-end hidden">
<li> Buttons here... </li>
</ul>
</div>

在页面上,我有以下JS:

document.addEventListener("DOMContentLoaded", function(event) {
const btnAnchor = document.getElementById('button-fab-anchor');
if (btnAnchor) {
const btnList = document.getElementById("button-fab-list");
const upIcon = document.getElementById("up-icon");
const downIcon = document.getElementById("down-icon");
btnAnchor.addEventListener("click",  function(event) {
if (event.target == btnAnchor) {
btnList.classList.toggle('hidden');
upIcon.classList.toggle('hidden');
downIcon.classList.toggle('hidden');
}
});
}
});

如果我点击按钮,但不点击按钮中的图标,这会很好。我已经尝试使用z-index将按钮父项放置在z-50,并将图标放置为z-10,以便父项堆叠在子项之上。

我错过了什么/我如何设置事件来处理按钮父项及其所有子项(即:图标(?

对按钮内的span使用pointer-events: none;
因为它是tailwindcss(在span上使用:pointer-events-none(,所以您有:

<button id="button-fab-anchor" class="...">
<span class="... pointer-events-none">
<i id="up-icon" class="fal fa-chevron-up"></i>
<i id="down-icon" class="fal fa-chevron-down hidden"></i>
</span>
</button>

addEventListener中,您有一个if条件,用于检查目标是否为btnAnchor(即#button-fab-anchor(。因此,如果事件目标是图标,则if条件不会是true

btnAnchor.addEventListener("click",  function(event) {
if (event.target == btnAnchor) {
btnList.classList.toggle('hidden');
upIcon.classList.toggle('hidden');
downIcon.classList.toggle('hidden');
}else{
//CLicked on something else. 
}
});

在代码中,if条件为if (event.target == btnAnchor)

当你点击图标时,目标对象是图标而不是按钮,所以js-core既没有进入块,也没有执行这个动作:

btnList.classList.toggle('hidden');
upIcon.classList.toggle('hidden');
downIcon.classList.toggle('hidden');

最新更新