CSS做一個Switch開關

來源:互聯網
上載者:User

標籤:ansi   charset   console   屬性   ack   htm   round   綁定   checkbox   

本文為博主原創,轉載請註明出處。  

 

  Switch開關:

  

  

 

  根據需求可知,Switch開關只有兩種選擇,true或false。所以我們想到HTML的checkbox控制項,用它來做。  

<input id="switch" type="checkbox" class="switch" />

  但是在瀏覽器中,checkbox是有固定形狀的(對勾),所以我們並不能直接修改checkbox的樣式。

  那我們該修改一個什麼東西的樣式變成開關呢?所以我們聯想到 label 標籤,為什麼呢?因為label標籤的for屬性可以綁定表單控制項,點擊label標籤,就相當於你點擊了綁定的那個控制項。

<label for="switch">test</label>

  

 

  廢話不多說,直接上完整代碼:  

<!DOCTYPE html><html>    <head>        <meta charset="utf-8" />        <title></title>        <link rel="stylesheet" href="css/test.css" />    </head>    <body>        <div class="container">            <input id="switch" type="checkbox" class="switch" />            <label for="switch" onclick="test()"></label>        </div>                <script>            var test = function(){               console.log(!document.getElementById(‘switch‘).checked ? "選中" : "未選中");            }        </script>    </body></html>

 

/*開關的大小*/.container {    height: 15px;    width: 30px;}/*設定checkbox不顯示*/.switch {    display: none;}/*設定label標籤為橢圓狀*/label {    display: block;    background-color: #EEEEEE;    height: 100%;    width: 100%;    cursor: pointer;    border-radius: 25px;}/*在label標籤內容之前添加如下樣式,形成一個未選中狀態*/label:before {    content: ‘‘;    display: block;    border-radius: 25px;    height: 100%;    width: 15px;    background-color: white;    opacity: 1;    box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);    -webkit-transition: all 0.2s ease;}/*在label標籤內容之後添加如下樣式,形成一個選中狀態*/label:after {    position: relative;    top: -15px;    left: 15px;    content: ‘‘;    display: block;    border-radius: 25px;    height: 100%;    width: 15px;    background-color: white;    opacity: 0;    box-shadow: 1px 1px 1px 1px rgba(0, 0, 0, 0.08);    -webkit-transition: all 0.2s ease;}/* ~ 兄弟選擇符。   p~ul :位於 p 元素之後的所有 ul 元素*//*選中後,選中樣式顯示*/#switch:checked~label:after {    opacity: 1;}/*選中後,未選中樣式消失*/#switch:checked~label:before {    opacity: 0;}/*選中後label的背景色改變*/#switch:checked~label {    background-color: green;}

 

CSS做一個Switch開關

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.