You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多次点击后按钮消失,forEach绑定同类元素交互功能故障求助

问题根源

  • 事件绑定的target捕获错误:你解构赋值的target是点击的实际元素,如果你点到箭头里的<i>标签,arrow变量实际指向的是<i>而不是.arr_container容器,active_arr类就加给了子元素,导致父容器没移位,状态完全混乱
  • 没有移除active_arr类的逻辑:你只在点击时加这个类,反向操作时从来没移除,多次点击后两个按钮都加了移位类,自然就看不到了
  • CSS语法错误:.box样式后面多了两个多余的},会导致后续部分样式优先级或匹配异常

修复方案

第一步:修正JS逻辑

const containerDivs = document.querySelectorAll('.box.center');
containerDivs.forEach(containerDiv => {
    const leftContainer = containerDiv.querySelector('.left_container');
    const arrow = containerDiv.querySelector('.arr_container');
    const cancel =  containerDiv.querySelector('.cancel');

    arrow.addEventListener("click", () => {
        // 直接用外层获取的arrow元素,不要用event.target避免匹配到子元素
        arrow.classList.add("active_arr");
        cancel.classList.remove("active_arr");
        if (leftContainer.classList.contains("off")) {
            leftContainer.classList.remove("off");
            leftContainer.classList.add("active");
        }
    });

    cancel.addEventListener("click", () => {
        // 直接用外层获取的cancel元素
        cancel.classList.add("active_arr");
        arrow.classList.remove("active_arr");
        if (leftContainer.classList.contains("active")) {
            leftContainer.classList.remove("active");
            leftContainer.classList.add("off")
        }
    });
});

第二步:修正CSS语法错误

删除.box样式后面多余的两个},同时删除无效的.arr_container .cancel选择器避免样式冲突,调整后的对应代码段:

.box{
    width: 250px;
    height: 250px; 
    box-shadow: 0 10px 20px rgba(0,0,0,0.288);
    border-radius: 23px;
    flex-direction: column;
    color: white;
    position: relative;
    overflow: hidden;
}
/*arrow*/
.arr_container{
    position: absolute;
    width: 50px;
    height: 50px;
    background: white;
    bottom: 0;
    right: 0;
    border-radius: 23px 0 23px 0;
    color: rgb(70,70,70);
    font-size: 1.6rem;
    cursor: pointer;
    transition: all .4s;
}

修改后多次点击按钮也不会出现消失问题,交互逻辑可以正常运行。

内容的提问来源于stack exchange,提问作者sajad.sharhani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 21:42:00