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

如何编写LESS/CSS选择器隐藏未禁用按钮后的所有后续元素

解决方案

原代码失效原因

你原来的写法只能匹配同一父级(同个.MyRow)下非disabled input后面的input元素,无法覆盖两种场景:

  • 同个.MyRow里该按钮后面非input类型的其他元素
  • 该按钮所在.MyRow之后的所有.MyRow容器及内部元素

CSS(LESS)实现方案(推荐,需要浏览器支持:has()选择器,当前主流现代浏览器均已支持)

.MyMainSection {
  /* 处理当前行内按钮后面的所有同级元素 */
  .MyRow {
    input:not([disabled]) ~ * {
      display: none;
    }
  }
  /* 处理按钮所在行后面的所有.MyRow容器 */
  .MyRow:has(input:not([disabled])) ~ .MyRow {
    display: none;
  }
}

代码说明

  • input:not([disabled]) ~ * 用通配符*替代原来的input,匹配同一行内该按钮之后所有类型的兄弟元素
  • .MyRow:has(input:not([disabled])) 先定位到包含非disabled按钮的行,再通过兄弟选择器~匹配该行之后所有的.MyRow容器,实现整行隐藏

兼容旧浏览器的JS实现方案

如果需要兼容不支持:has()的旧版浏览器,可以用少量JS实现:

// 定位唯一的非disabled按钮
const enableBtn = document.querySelector('.MyMainSection input:not([disabled])')
if (enableBtn) {
  // 隐藏按钮所在行内,按钮后方的所有同级元素
  let sibling = enableBtn.nextElementSibling
  while (sibling) {
    sibling.style.display = 'none'
    sibling = sibling.nextElementSibling
  }
  // 隐藏按钮所在行后方的所有.MyRow行
  let row = enableBtn.closest('.MyRow').nextElementSibling
  while (row) {
    row.style.display = 'none'
    row = row.nextElementSibling
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:15:03