:checked选择器应用 自定义单/多选框选中时的样式

本文介绍了如何利用CSS:checked伪类选择器,结合radio按钮和隐藏的input元素,实现自定义的选中/未选中样式。通过示例代码展示了如何在用户选择后改变元素的样式,例如更改图片背景。示例中,单次和往返行程的选项通过此方法实现了不同的视觉效果。
摘要由CSDN通过智能技术生成

 在MDN官网,:checked选择器有如下定义:

:checked CSS 伪类选择器表示任何处于选中状态的radio(<input type="radio">), checkbox (<input type="checkbox">) 或("select") 元素中的option HTML元素("option")。

用户通过勾选/选中元素或取消勾选/取消选中,来改变该元素的 :checked 状态。

基础示例

该实例有以下几个需求:

  1. 将两个input标签隐藏,自定义选中/未选中的样式(借用隐藏的radio来切换元素的样式);
  2. 选择后通过: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;
}

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Gavi曦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值