css如何实现点击改变颜色

广告:宝塔Linux面板高效运维的服务器管理软件 点击【 https://www.bt.cn/p/uNLv1L 】立即购买

css如何实现点击改变颜色

方法:1、使用“:active”伪类,配合“:focus”伪类,只需要将“:active”伪类和“:focus”伪类设置相同背景颜色即可实现效果;2、使用tabindex属性控制次序,配合“:focus”伪类实现点击后变色,且不消失效果。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。

可通过使用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>
登录后复制

效果:

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视频教程

以上就是css如何实现点击改变颜色的详细内容,更多请关注9543建站博客其它相关文章!

广告:SSL证书一年128.66元起,点击购买~~~

9543建站博客
一个专注于网站开发、微信开发的技术类纯净博客。

作者头像
admin创始人

肥猫,知名SEO博客站长,14年SEO经验。

上一篇:如何获取dom内class的值
下一篇:html5桌面通知之Notification API详解

发表评论

关闭广告
关闭广告