在MDN官网,:checked选择器有如下定义:
:checked
CSS 伪类选择器表示任何处于选中状态的radio(<input type="radio">
), checkbox (<input type="checkbox">
) 或("select") 元素中的option HTML元素("option")。
用户通过勾选/选中元素或取消勾选/取消选中,来改变该元素的 :checked 状态。
基础示例
该实例有以下几个需求:
- 将两个input标签隐藏,自定义选中/未选中的样式(借用隐藏的radio来切换元素的样式);
- 选择后通过:checked选择器来改变选中样式(样例中是更改图片)
如下代码所示
<div class="way-type">
<p>行程类型</p>
<form action="" class="ifreturn">
<input type="radio" value="once" name="ifreturn" id="once">
<label for="once"><img src="./assets/danxuanno.svg" alt="" class="once-img"> <p>单次</p> </label>
<input type="radio" value="twice" name="ifreturn" id="twice" checked="checked">
<label for="twice"><img src="./assets/danxuanno.svg" alt="" class="twice-img"> <p>往返</p> </label>
</form>
</div>
.way-type {
display: flex;
height: 19px;
align-items: center;
margin-top: 14px;
}
.way-type>p {
width: 56px;
height: 19px;
font-family: MicrosoftYaHei;
font-size: 14px;
color: #666666;
letter-spacing: 0;
text-align: center;
font-weight: 400;
margin-left: 24.5px;
}
/*自定义label样式*/
#once,
#twice {
display: none;
}
.ifreturn {
display: flex;
margin-left: 23.5px;
}
.ifreturn label {
height: 19px;
display: flex;
align-items: center;
}
.ifreturn label:last-of-type {
margin-left: 22px;
}
.ifreturn label p {
width: 28px;
height: 19px;
line-height: 19px;
font-family: MicrosoftYaHei;
font-size: 14px;
color: #1E1E1E;
letter-spacing: 0;
text-align: center;
font-weight: 400;
margin-left: 7px;
}
.once-img,
.twice-img {
display: inline-block;
width: 14px;
height: 14px;
}
#once:checked~* .once-img,
#twice:checked~* .twice-img {
width: 14px;
height: 14px;
background-image: url(../assets/danxuan.svg);
background-size: 100%;
background-repeat: no-repeat;
}