天天看點

CSS僞類的一些用法以及visibility:hidden和display:none的一些差別

版權聲明: 本文由 一隻部落格 發表于 bloghome部落格

文章連結: https://www.bloghome.com.cn/user/cnn237111

CSS僞類有比較實用的用處,可以使程式員少些一些js,而實作特定的效果。

w3cschool中,僞類有如下的幾種:

:active  向被激活的元素添加樣式。

:focus  向擁有鍵盤輸入焦點的元素添加樣式。 

:hover 當滑鼠懸浮在元素上方時,向元素添加樣式。 

:link 向未被通路的連結添加樣式。

:visited 向已被通路的連結添加樣式。

:first-child 向元素的第一個子元素添加樣式。

:lang 向帶有指定 lang 屬性的元素添加樣式。

本文說一下focus僞類,因為比較實用。

比如某些場合,需要對文本框輸入時,背景色變色。用jquery固然可以寫。通過onfocus事件綁定特定的執行代碼。

此時用focus僞類則效率高了很多,也不需要寫額外的JS代碼。特别對于動态生成的表單,也不需要使用jquery的live方法了。注意,使用僞類的時候,務必把DOCTYPE寫完整,不然會不起作用。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
    <style type="text/css">.testclass{border: 1px solid black;width: 50px;
        }        .testclass:focus
        {background-color: red;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $("#btn").click(function () {
                $("body").append("<input class=\"testclass\" type=\"text\" />");
            })
        });
    </script>
</head>
<body>
    <input id="btn" type="button" value="add textbox" />
    <input class="testclass" type="text" />
</body>
</html>      

visibility: hidden和display: none的差別在于,隐藏後,是否還占着位子。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html>
<head>
    <title></title>
    <script src="http://code.jquery.com/jquery-1.7.2.min.js" type="text/javascript"></script>
    <style type="text/css">.use_visibility{visibility: hidden;
        }.use_diplay{display: none;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            $("#btn_use_visibility").click(function () {
                $("#txt_use_visibility").toggleClass("use_visibility");
            });
            $("#btn_use_diplay").click(function () {
                $("#txt_use_diplay").toggleClass("use_diplay");
            });
        });
    </script>
</head>
<body>
    <input id="btn_use_visibility" type="button" value="use_visibility" />
    <input id="btn_use_diplay" type="button" value="use_diplay" /><br/>
    <input id="txt_use_visibility" type="text" />文字
    <br/>
    <input id="txt_use_diplay" type="text" />文字
</body>
</html>