css实现颜色切换

平时我们写代码的时候,可能会碰到类似这样的需求,比如有一个滚动区域来展示一些内容,一个竖着的导航条显示进度,随着滚动的进行,导航条对应的元素改变颜色(参考微信的通讯录)。然后做一个小的demo来实现基础的颜色切换。

示例代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width:200px;
            height:200px;
            border:1px solid black;
            display:flex;
            flex-direction: row;
            justify-content: center;
            align-items: center;
        }

        .box .circle{
            width:20px;
            height:20px;
            border-radius:50%;
            margin-left:10px;
            background-color: orange;
        }

        .box .circle:focus{
            background-color: blue;
        }
    </style>
</head>
<body>
    <div class = "box">
        <div class = "circle" tabindex="1"></div>
        <div class = "circle" tabindex="1"></div>
        <div class = "circle" tabindex="1"></div>
        <div class = "circle" tabindex="1"></div>
        <div class = "circle" tabindex="1"></div>
    </div>
</body>
</html>

效果图如下:

在这里插入图片描述
纯css的话,我们可通过使用css伪类实现点击元素变色的效果,两个伪类分别是:active, :focus:active它让页面能在浏览器监测到激活时给出反馈。当用鼠标交互时,它代表的是用户按下按键和松开按键之间的时间。:focus在用户点击或触摸元素或通过键盘的 “tab” 键选择它时会被触发。

至于为什么选择:focus,大家一试便知。:active,元素被点击时变色,但颜色在点击后消失。:focus,元素被点击后变色,且颜色在点击后不会消失。

但是div等元素无法接受键盘或其他用户事件,即不支持:focus伪类。使用tabIndex属性控制次序,配合“:focus”伪类实现点击后变色,且不消失效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值