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

JS实现手风琴效果时无法获取包裹的img元素添加rotate类

问题根源

你之前尝试更换DOM选择器、移除div包裹img都没解决问题,核心原因有三个:

  • 现有逻辑仅实现了.question元素上open类的切换,完全没有编写针对内部.arrow箭头元素的类名增删逻辑
  • 查找箭头元素时没有限定查找范围,直接全局匹配.arrow会选中页面所有箭头,无法精准定位当前点击问题下的对应箭头
  • 额外体验问题:当前用display: none/block切换答案显隐的写法,你写的transition过渡动画完全不生效,display属性不支持CSS过渡。
修复方案
  1. 所有DOM查找操作限定在当前点击的.question元素范围内,通过element.querySelector('.arrow')精准定位当前项对应的箭头
  2. 切换问题项open类的同时,同步操作对应箭头的rotate类:展开项加rotate,关闭项移除rotate,包括关闭其他已展开项时也要同步重置对应箭头的状态
  3. 把答案区的显隐逻辑从display切换改为max-height切换,同时给箭头加旋转过渡,让交互更流畅
修正后代码

JavaScript

const questionList = document.querySelectorAll('.question')

questionList.forEach(question => {
    question.addEventListener('click', () => {
        const currentArrow = question.querySelector('.arrow')
        // 当前项是展开状态,执行关闭
        if (question.classList.contains('open')) {
            question.classList.remove('open')
            currentArrow.classList.remove('rotate')
            return
        }
        // 先关闭所有已展开的项,重置对应箭头状态
        const openedQuestions = document.querySelectorAll('.question.open')
        openedQuestions.forEach(openItem => {
            openItem.classList.remove('open')
            openItem.querySelector('.arrow').classList.remove('rotate')
        })
        // 展开当前点击项,给箭头加旋转类
        question.classList.add('open')
        currentArrow.classList.add('rotate')
    })
})

CSS

.question + .answer {
    max-height: 0;
    overflow: hidden;
    transition: all ease 1s;
}

.question.open + .answer {
    /* 该值设置为大于答案区域最大内容高度即可 */
    max-height: 200px;
}

.arrow {
    /* 给箭头添加旋转过渡,效果更自然 */
    transition: transform 0.3s ease;
}

.arrow.rotate {
    transform: rotate(180deg);
}

HTML(原有结构无需修改)

<div class="container">
  <div class="question">How many team members can I invite?
    <img class="arrow" src="./images/icon-arrow-down.svg">
  </div>
  <div class="answer">You can invite up to 2 additional users on the Free plan. There is no limit on 
    team members for the Premium plan.</div>
</div>

内容的提问来源于stack exchange,提问作者FruitySryup

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 08:54:19