可通过使用CSS伪类实现点击元素变色的效果,两个伪类是:active, :focus

1、:active:用于选择活动链接。当在一个链接上点击时,它就会成为活动的(激活的),:active选择器适用于所有元素,不仅限于链接a元素

:focus:用于选取获得焦点的元素。仅接收键盘事件或其他用户输入的元素允许 :focus 选择器。

由于上面的特性,如果想实现点击时变色效果,有以下两种方法,两者区别在

:active,元素被点击时变色,但颜色在点击后消失

:focus, 元素被点击后变色,且颜色在点击后不消失

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>document</title> 
<style>
    button:active{
        background:olive;
    }
    button:focus{
        background:olive;
    }
</style>
</head> 
<body bgcolor="#ccc">
    <button>cmcc</button>
        
</body> 
</html>

效果:

css如何实现点击改变颜色

2、由于div等元素无法接受键盘或其他用户事件,即不支持:focus伪类,可通过增加tabIndex属性使其支持:focus

<!DOCTYPE html> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>document</title> 
<style>
    div{
        background: #fff;
        border:1px solid rgb(59, 59, 59);
        border-radius: 5px;
        margin: 10px 0;
    }
    div:focus {
            background-color:red;
        }
</style>
</head> 
<body bgcolor="#ccc">
    <div tabindex="1">
        Section 1
        </div>
        
        <div tabindex="2">
        Section 2
        </div>
        
        <div tabindex="3">
        Section 3
        </div>
        
</body> 
</html>

效果:

css如何实现点击改变颜色

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。