css如何实现点击改变颜色


本文摘自PHP中文网,作者醉折花枝作酒筹,侵删。

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

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

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

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

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

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

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<!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

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

<!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如何实现点击改变颜色的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

了解一些 提高前端开发效率的 css 属性选择器

css怎么控制按钮不可用

css的作用是什么

如何利用css改变浏览器滚动条样式

display:inline是什么意思?

简述什么是css

css中position的定位有哪些

id在css中怎么表示什么

如何清除css缓存

css transition-delay属性怎么用

更多相关阅读请进入《css》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...