平时我们写代码的时候,可能会碰到类似这样的需求,比如有一个滚动区域来展示一些内容,一个竖着的导航条显示进度,随着滚动的进行,导航条对应的元素改变颜色(参考微信的通讯录)。然后做一个小的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”伪类实现点击后变色,且不消失效果。