[CSS3] 学习笔记-选择器详解(三)

时间:2023-03-09 13:33:39
[CSS3] 学习笔记-选择器详解(三)

1、UI元素状态伪类选择器

在CSS3的选择器中,除了结构性伪类选择器外,还有一种UI元素伪类选择器。这些选择器的共同特征是:指定的样式只有当元素处于某种状态时才起作用,在默认状态下不起作用。在CSS3中,共有17种UI元素伪类选择器,分别是:

E:hover, E:active, E:focus, E:disabled, E:read-only, E:checked, E:default, E:indeterminate, E:selection, E:invalid, E: valid, E:required, E:optional, E:in-range

 <!doctype html>
 <html>
 <head>
     <meta charset="utf-8">
     <title></title>
     <!--hover、focus、active-->
     <style>
         /*鼠标经过时,输入框会变成如下颜色*/
         input[type="text"]:hover{
             background-color: red;
         }
         /*鼠标点击过后,会变成如下颜色*/
         input[type="text"]:focus{
             background-color: gold;
         }
         /*鼠标按下,会变成如下颜色*/
         input[type="text"]:active{
             background-color: green;
         }

         /*选中checkbox后,checkbox会有黄色边框*/
         input[type="checkbox"]:checked{
             outline: 2px solid gold;
         }
     </style>
 </head>
 <body>
     <input type="text" name="name">
     <input type="text" name="age">

     <input type="checkbox">阅读
     <input type="checkbox">旅游
     <input type="checkbox">电影
     <input type="checkbox">上午
 </body>
 </html>

enabled和disable选择器的例子:

 <!doctype html>
 <html>
 <head>
     <meta charset="utf-8">
     <title></title>
     <!--enabled,disabled-->
     <style>
         /*可用的状态为金色,不可用的状态为灰色*/
         input[type="text"]:enabled{
             background-color: gold;
         }
         input[type="text"]:disabled{
             background-color: gray;
         }
     </style>
 </head>
 <body>
     <script>
         function radio_change(){
             var radio1 = document.getElementById("radio1");
             var radio2 = document.getElementById("radio2");
             var text=document.getElementById("text");
             if(radio1.checked){
                 text.disabled="";
             }else {
                 text.value = "";
                 text.disabled = "disabled";
             }
         }
     </script>
     <input type="radio" id="radio1" name="radio" onchange="radio_change()">可用
     <input type="radio" id="radio2" name="radio" onchange="radio_change()">不可用
     <input type="text" id="text" disabled>
 </body>
 </html>

2、通用兄弟元素选择器  

通用兄弟元素选择器,用来指定位于同一个父元素之中的某个元素之后的所有其他某个种类的兄弟元素所使用的样式。

div~p:表示div和P元素位于同一个父元素,为这个div之后的p元素,指定样式

 <!doctype html>
 <html>
 <head>
     <meta charset="utf-8">
     <title></title>
     <style>
         /*下面指的是子级中的div元素~把与他相邻的P元素,指定为黄色*/
         div~p{
             background-color: gold;
         }
     </style>
 </head>
 <body>
     <div>
         <div>
             <p>P元素为div的子元素</p>
             <p>P元素为div的子元素</p>
             <p>P元素为div的子元素</p>
         </div>
         <!--以下的P元素,相对上面的div元素,是兄弟的关系-->
         <p>P元素为div的子元素</p>
         <p>P元素为div的子元素</p>
         <p>P元素为div的子元素</p>
     </div>
 </body>
 </html>