Featured image of post 纯CSS实现选项选择效果

纯CSS实现选项选择效果

灵活使用checked伪类选择器实现元素单选多选效果

先看效果

你可以通过点击来切换不同的选项,而这个样例没有使用js而是完全使用css实现的。

:checked伪类选择器

实现这个效果的核心是:checked伪类选择器。这个选择器可以匹配被用户点击的元素,也就是说我们能为用户选择的元素单独设置样式。

废话不多说,直接上代码。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
    <div class="cont">
        <!-- 首先创建input元素,虽然它不会显示,但是我们需要它才能使元素可以被选择 -->
        <input checked type="radio" id="radio1" name="radio"/>
        <!-- 然后在input后紧接着一个lable,通过for属性与上边的input绑定,这样点击这个lable就等价于点击了input -->
        <label for="radio1">选项1</label>
        <!-- 如法炮制几个选项 -->
        <input type="radio" id="radio2" name="radio"/>
        <label for="radio2">选项2</label>
        <input type="radio" id="radio3" name="radio"/>
        <label for="radio3">选项3</label>
        <input type="radio" id="radio4" name="radio"/>
        <label for="radio4">选项4</label>
    </div>
    <style>
        .cont{
            display: flex;//为容器设置弹性布局使其内部元素横向排布。
            line-height: 120px;
            text-align: center;
        }
        label{//这里就是lable的样式啦。
            margin-right: 10px;
            width: 60px;
            height: 120px;
            background: #ccc;
            border-radius: 10px;
            transition-duration:.3s;
        }
        input{
            display: none;//隐藏input元素,它只是工具人而已。
        }
        input:checked + label{//使用checked找到被用户点击的input,再通过+相邻兄弟选择器选择到这个input后紧挨着的lable,为它设置样式。
            transition-duration:.3s;
            width: 120px;
            background:#99e6ff;
            color:#006080;
        }
    </style>

在上边的代码中我们利用了<input type="radio">可以被用户点击的特性,然后再将lable元素与其绑定并放置在其后边。这样不仅可以通过点击lable来选中input,还能使用相邻兄弟选择器通过 input来选中lable。 此时作为工具人的input元素就能从页面中隐藏了,我们只需要为可操作性更强的lable元素设计样式即可。 使用这种技巧能实现的效果能远超你的想象。

相关知识

input的radio类型;

:checked伪类选择器;

相邻兄弟选择器;

lable及其for属性

Licensed under CC BY-NC-SA 4.0
最后更新于 Sep 25, 2024 00:00 UTC
使用 Hugo 构建
主题 StackJimmy 设计