调用classList.remove()移除类成功但元素内容仍显示怎么解决
问题原因
- 你移除
.start_btn类仅会清除该类对应的flex布局、80vh高度等样式,承载按钮的div元素本身以及内部的按钮没有被设置隐藏规则,所以按钮仍然会显示在页面上。 - 你之前定义的
.hide.start_btn组合选择器无法生效:你在触发点击时已经移除了元素的start_btn类,添加的hide类无法匹配该组合选择器,自然不会生效。
解决方案(二选一即可)
方案1:添加隐藏类实现消失效果
修改CSS中的hide类,去掉和start_btn的绑定,直接设置通用隐藏规则:
.hide { display: none !important; }
修改JS逻辑,不需要移除start_btn类,直接给容器加隐藏类即可:
const startbtn = document.querySelector(".start_btn"); const infoBox = document.querySelector(".info_box"); startbtn.addEventListener('click', function(){ startbtn.classList.add("hide"); infoBox.classList.add("showInfoBox"); })
方案2:直接从DOM树移除整个按钮容器
如果后续不需要再显示开始按钮,可以直接删除整个容器元素,JS修改为:
const startbtn = document.querySelector(".start_btn"); const infoBox = document.querySelector(".info_box"); startbtn.addEventListener('click', function(){ // 直接移除整个按钮容器DOM元素 startbtn.remove(); infoBox.classList.add("showInfoBox"); })
可选优化
你现有代码中.showInfoBox.info_box的选择器可以简化为直接写.showInfoBox,逻辑是一致的,代码更简洁。
内容的提问来源于stack exchange,提问作者StillLearning
相关产品推荐
相关产品推荐

