You need to enable JavaScript to run this app. 已移除关联的CSS类但对应样式仍未失效,项目卡片无法收起
优惠活动
大模型
产品
解决方案
定价
更多

已移除关联的CSS类但对应样式仍未失效,项目卡片无法收起

问题背景

HTML、CSS和JavaScript领域新手在实现项目卡片展开/收起交互时,遇到了类移除后样式无回落的异常,具体现象为:

  • 点击id为project1、project2的div元素时,通过showProject()函数给对应元素附加.expand、.info_expand、.icon_expand三个类,元素会正常触发样式过渡,呈现全展开效果
  • 后续点击关闭按钮触发hideProject()函数,手动移除上述三个类后,元素并未回到初始未展开的样式,仍然保持展开后的显示状态
已实现的代码片段

HTML结构

<!DOCTYPE HTML>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
</head>
<body>
    <div class="container" style="margin-top: 200px;">
        <div class="project showScroll" id="project1" onclick="showProject('1')">
            <p style="font-size: 30px;">1. Projekt</p>
            <button class="custom_button" id="close1" onclick="hideProject('1')"><i class="material-icons">close_fullscreen</i></button>
            <div id="projectText1" class="prjText">
                <p>Here is the information</p>
            </div>
        </div>
        <div class="project showScroll" id="project2" onclick="showProject('2')">
            <p style="font-size: 30px;">2. Projekt</p>
            <button class="custom_button" id="close2" onclick="hideProject('2')"><i class="material-icons">close_fullscreen</i></button>
            <div id="projectText2" class="prjText">
                <p>Here is the information</p>
            </div>
        </div>
    </div>
    <script src="scripts.js"></script>
</body>
</html>

样式表(CSS)

body {
    margin: 0;
    background-color: black;
    overflow: auto;
}

.container {
    position: relative;
    top: 50px;
    margin-bottom: 50px;
    margin-left: 250px;
}

.project {
    width: 100px;
    height: 100px;
    position: relative;
    color: white;
    background-color: rgb(0, 153, 51);
    margin: 100px 0px;
    vertical-align: middle;
    line-height: 100px;
    transition: width 2s,
                padding-left 2s,
                height 2s;
    will-change: width, padding-left, height;
    cursor: pointer;
}

.project.isVisible {
    width: 650px;
    padding-left: 50px;
}

.project.isVisible.expand {
    width: 80%;
    height: 500px;
}

.prjText {
    position: relative;
    left: -27px;
    top: -50px;
    height: 0px;
    color: rgba(0,0,0,0);
    background-color: white;
    padding-left: 50px;
    cursor: pointer;
    transition: height 2s,
                color 0s,
                background-color 0s;
    will-change: height, color, background-color;
}

.prjText.info_expand {
    height: 400px;
    color: black;
    background-color: white;
}

.custom_button {
    border-color: black;
    border-style: solid;
    color: white;
    background-color: rgb(0, 153, 51);
    opacity: 0;
    left: 650px;
    top: 25px;
    position: absolute; 
    transition: opacity 2s,
                left 2s;
    will-change: opacity, left;
}

.custom_button.icon_expand {
    opacity: 1;
    left: 995px;
}

交互脚本(JavaScript)

// 1. 滚动监听动画
var scroll = window.requestAnimationFrame ||
             // IE 兼容降级
             function(callback){ window.setTimeout(callback, 1000/60)};
var elementsToShow = document.querySelectorAll('.showScroll'); 

function loop() {
    Array.prototype.forEach.call(elementsToShow, function(element){
      if (isElementInViewport(element)) {
        element.classList.add('isVisible');
      } else {
        // 原逻辑注释:离开视口时移除isVisible类
        // element.classList.remove('isVisible');
      }
    });
    scroll(loop);
}

// 首次触发循环监听
loop();

// 视口检测工具函数
function isElementInViewport(el) {
  // 兼容jQuery传入元素的场景
  if (typeof jQuery === "function" && el instanceof jQuery) {
    el = el[0];
  }
  var rect = el.getBoundingClientRect();
  return (
    (rect.top <= 0 && rect.bottom >= 0)
    ||
    (rect.bottom >= (window.innerHeight || document.documentElement.clientHeight) &&
      rect.top <= (window.innerHeight || document.documentElement.clientHeight))
    ||
    (rect.top >= 0 &&
      rect.bottom <= (window.innerHeight || document.documentElement.clientHeight))
  );
}

// 2. 项目展开/收起逻辑
function showProject(no){
    var prj = "project" + no;
    var element = document.getElementById(prj);
    element.classList.add("expand");
    document.getElementById("projectText" + no).classList.add("info_expand");
    document.getElementById("close" + no).classList.add("icon_expand");
}

function hideProject(no){
    var prj = "project" + no;
    var element = document.getElementById(prj);
    element.classList.remove("expand");
    document.getElementById("projectText" + no).classList.remove("info_expand");
    document.getElementById("close" + no).classList.remove("icon_expand");
}
异常原因解析
  • 首先看CSS样式的匹配逻辑:.project的初始默认样式为width: 100px; height: 100px,当滚动检测触发给元素加上.isVisible类后,样式会变为width: 650px; padding-left: 50px;全展开样式的规则是.project.isVisible.expand,仅当元素同时带有isVisible和expand两个类时,才会应用width: 80%; height: 500px的全展开尺寸
  • 当触发hideProject移除expand类后,元素上仍然保留滚动监听添加的isVisible类,此时样式会匹配.project.isVisible规则,也就是维持650px宽度、50px左内边距的半展开状态,而非回到最开始100px宽度的初始视觉状态,容易给人“类没移除成功”的错觉
  • 核心交互逻辑漏洞:关闭按钮是.project div的内部子元素,点击关闭按钮触发hideProject收起样式后,点击事件会冒泡到外层绑定了onclick="showProject()"的.project div上,立刻又触发展开逻辑,相当于刚收起就被重新展开,直接导致样式看起来完全没有回落
调整方案
  • 给关闭按钮的点击事件添加阻止冒泡逻辑:在hideProject函数开头加上event.stopPropagation(),避免点击关闭按钮时连带触发外层div的展开事件
  • 调整CSS样式的耦合关系:将全展开的样式规则从.project.isVisible.expand改为.project.expand,减少对isVisible类的依赖,避免多类名叠加导致的样式匹配异常
  • 如果需要收起后回到页面初始的100px窄尺寸,可在hideProject函数中同步移除元素上的isVisible类;如果只需要回到滚动触发的半展开宽度(650px),解决冒泡问题后即可正常实现收起效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.26 16:54:05