如何在CSS中当另一个元素处于:active状态时设置其属性值?
问题:无JavaScript电灯开关,如何在元素
:active状态下修改另一个元素的CSS属性 我正在制作一个无JavaScript的电灯开关,遇到的问题是:不知道如何在一个元素处于:active状态时,设置另一个元素的CSS属性。尝试了一些方法但都没有效果,相关代码如下:
HTML代码
<div class="wall-switch"> <div class="screw"> <svg class="icon icon--plus" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" fill="rgba(0, 0, 0, 0.45)"> <path d="M24 10h-10v-10h-4v10h-10v4h10v10h4v-10h10z" stroke="url(#grad1)" /> </svg> </div> <div class="padding"></div> <div class="switch"></div> <div class="padding"></div> <div class="screw"> <svg class="icon icon--plus" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" fill="rgba(0, 0, 0, 0.45)"> <path d="M24 10h-10v-10h-4v10h-10v4h10v10h4v-10h10z" stroke="url(#grad1)" /> </svg> </div> </div>
CSS代码
body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: gray; overflow: hidden; filter: brightness(100%); } .wall-switch { background-color: #ebebeb; width: 300px; height: 500px; box-shadow: inset -10px -10px 22px 0px rgba(255, 255, 255, 1), inset 10px 10px 22px 0px rgba(0, 0, 0, 0.30); display: flex; align-items: center; flex-direction: column; padding: 25px; border-radius: 4px; } .screw { padding: 7.5px; border-radius: 20px; display: flex; align-items: center; justify-content: center; box-shadow: inset 2.5px 2.5px 10px 0px rgba(255, 255, 255, 1), inset -2.5px -2.5px 10px 0px rgba(0, 0, 0, 0.30), 0px 0px 2px 1px rgba(0, 0, 0, 0.40); } .icon { transition-duration: 10s; transition-timing-function: linear; } .icon:active { transform: rotate(-3600deg); } .padding { padding: 55px; } .switch { width: 105px; height: 200px; box-shadow: 0px 0px 2px 1px rgba(0, 0, 0, 0.40), inset 0px 95px 20px 0px #ebebeb, inset 0px -95px 20px 0px rgba(0, 0, 0, 0.20); border-radius: 2.5px; } .switch:active { box-shadow: 0px 0px 2px 1px rgba(0, 0, 0, 0.40), inset 0px -95px 20px 0px #6b6b6b, inset 0px 95px 20px 0px rgba(0, 0, 0, 0.20); } .switch:active .wall-switch { background-color: #6b6b6b; }
解决方案
你写的.switch:active .wall-switch选择器无效,原因是CSS选择器只能向下选择后代、兄弟或后续元素,无法向上选择父元素——.switch是.wall-switch的子元素,所以没法通过子元素的:active直接修改父元素样式。这里提供两种可行方案:
方案1:使用:has()伪类(推荐,现代浏览器支持)
:has()伪类可以让父元素检测子元素的状态,直接替换你无效的选择器:
/* 替换原来的.switch:active .wall-switch */ .wall-switch:has(.switch:active) { background-color: #6b6b6b; }
这样点击.switch时,父元素.wall-switch的背景色会同步变化,同时保留.switch:active的原有样式,完全符合需求。
方案2:调整交互触发元素(兼容旧浏览器)
如果需要兼容不支持:has()的旧浏览器,可以把:active绑定到父元素.wall-switch上,同时给.switch加上鼠标样式提示:
.wall-switch:active { background-color: #6b6b6b; } .switch { cursor: pointer; /* 提示可点击 */ }
缺点是点击开关面板的任何区域都会触发背景变化,但如果面板只有开关是交互区域,这个方案也能接受。
另外,建议给.switch加上cursor: pointer,提升用户交互体验。
内容的提问来源于stack exchange,提问作者Really Bad Dev
相关产品推荐
相关产品推荐

