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

如何检测类的CSS属性状态并据此修改其他元素的样式属性

实现方案

可以通过CSS选择器或JS两种方式实现,以下是具体代码:

方案1:CSS :has() 选择器实现(现代浏览器场景优先)

利用CSS新增的:has()选择器匹配父级元素,直接关联toggle按钮的active状态和侧边栏、内容区的样式,新增以下CSS代码即可:

/* 匹配包含active类toggle按钮的header,选中其后的main内的对应元素 */
.header:has(.toggle-sidebar.active) + .main .sidebar {
  width: 0;
  overflow: hidden;
}
.header:has(.toggle-sidebar.active) + .main .content {
  margin-left: 0;
}

如果需要增加收起/展开的平滑过渡效果,修改原有CSS如下:

.sidebar{
    width: 60px;
    /* 新增过渡和溢出隐藏 */
    transition: width 0.3s ease;
    overflow: hidden;
}
  
.content{
    margin-left: 60px;
    /* 新增过渡 */
    transition: margin-left 0.3s ease;
}

注::has()选择器支持Chrome 105+、Firefox 121+、Safari 15.4+,覆盖绝大多数现代浏览器场景

方案2:JS实现(兼容所有浏览器场景)

如果需要兼容不支持:has()选择器的旧浏览器,通过JS绑定点击事件切换状态即可:

const toggleBtn = document.querySelector('.toggle-sidebar');
const sidebar = document.querySelector('.sidebar');
const content = document.querySelector('.content');

toggleBtn.addEventListener('click', function() {
  // 切换按钮自身active状态
  this.classList.toggle('active');
  // 同步修改侧边栏和内容区样式
  if (this.classList.contains('active')) {
    sidebar.style.width = '0';
    content.style.marginLeft = '0';
  } else {
    sidebar.style.width = '60px';
    content.style.marginLeft = '60px';
  }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 14:15:03