我正在尝试根据 select 元素中所做的选择来设置我的框背景颜色的样式。 挑战是在这里使用 :has() 伪类。 我已经检查过这行代码好几次了,它与选项中选择的内容不符...... 我在这里做错了什么?
HTML 代码片段
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="testing.css">
</head>
<body>
<div class="selections">
<select name="" id="" class="options">
<option value="green">Green colour</option>
<option value="red">Red colour</option>
<option value="blue">Blue colour</option>
<option value="yellow">Yellow colour</option>
</select>
</div>
<div class="parentBox">
<div class="box">box</div>
</div>
</body>
</html>
CSS 代码片段
.selections {
display: flex;
align-items: center;
justify-content: center;
height: 30vh;
}
.options {
width: 30%;
height: 30%;
}
.parentBox {
display: flex;
align-items: center;
justify-content: center;
height: 40vh;
}
.box {
box-shadow: 8px 8px 32px;
width: 50%;
height: 50%;
}
.selections:has(select > option[value="green"])+.parentBox>.box{
background-color: limegreen;
box-shadow: -8px -8px 16px darkgreen;
}
.selections:has(select > option[value="red"])+.parentBox>.box{
background-color: firebrick;
box-shadow: -8px -8px 16px red;
}
您需要添加
:checked
伪类,以便样式仅应用于所选选项:
https://codepen.io/jimmys20/pen/oNdWxrr
.selections {
display: flex;
align-items: center;
justify-content: center;
height: 30vh;
}
.options {
width: 30%;
height: 30%;
}
.parentBox {
display: flex;
align-items: center;
justify-content: center;
height: 40vh;
}
.box {
box-shadow: 8px 8px 32px;
width: 50%;
height: 50%;
}
.selections:has(select > option[value="green"]:checked)+.parentBox>.box{
background-color: limegreen;
box-shadow: -8px -8px 16px darkgreen;
}
:root {
--bg-color: transparent;
--shadow-color: transparent;
}
.parentBox > .box {
background-color: var;
box-shadow: -8px -8px 16px red;
}
.selections:has(select > option[value="red"]:checked)+.parentBox>.box{
background-color: firebrick;
box-shadow: -8px -8px 16px red;
}
<body>
<div class="selections">
<select name="" id="" class="options">
<option value="green">Green colour</option>
<option value="red">Red colour</option>
<option value="blue">Blue colour</option>
<option value="yellow">Yellow colour</option>
</select>
</div>
<div class="parentBox">
<div class="box">box</div>
</div>
</body>