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

使用CSS或Tailwind点击主按钮修改所有.two类元素背景色的问题

问题原因

你当前使用的选择器button.one:focus~div.two中的~是CSS后续兄弟选择器,仅能匹配和当前元素属于同一个父元素、且出现在当前元素之后的同级兄弟元素。你代码里外层的.two元素和按钮.one不在同一个父div下,自然无法被该选择器命中,确实是元素层级结构导致的问题。

不删除现有div的实现方案

方案1:纯CSS实现(适配现代浏览器)

修改CSS规则,用:has()选择器匹配包含聚焦按钮的父元素,再选中内部和后续同级的所有.two元素:

div:has(> button.one:focus) div.two,
div:has(> button.one:focus) ~ div.two {
  background-color: rgba(185, 28, 28, 1);
}

注::has()选择器已兼容Chrome、Firefox、Safari等绝大多数主流浏览器,若需要兼容更旧的浏览器版本可使用JS方案。

方案2:JS实现(全版本兼容)

给按钮添加聚焦/失焦事件监听,统一控制所有.two元素的样式:

const mainBtn = document.querySelector('button.one')
const allTwoEl = document.querySelectorAll('.two')
// 聚焦时变红
mainBtn.addEventListener('focus', () => {
  allTwoEl.forEach(el => el.style.backgroundColor = 'rgba(185, 28, 28, 1)')
})
// 可选:失焦时恢复原有样式
mainBtn.addEventListener('blur', () => {
  allTwoEl.forEach(el => el.style.backgroundColor = '')
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:06:10