首頁 > web前端 > css教學 > 主體

如何使用純CSS實現電源開關控制項(附源碼)

不言
發布: 2018-09-27 16:07:51
原創
3116 人瀏覽過

這篇文章帶給大家的內容是關於如何使用純CSS實現電源開關控制(附源碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

效果預覽

如何使用純CSS實現電源開關控制項(附源碼)


原始程式碼下載

#https:/ /github.com/comehop​​e/front-end-daily-challenges

程式碼解讀

定義dom,包含3 個元素,分別代表input 控制、開關和燈光:

登入後複製

居中顯示:

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #eee;
}
登入後複製

定義控制項的樣式,把控制項的設定為透明,使其不可見,但仍可與使用者互動。其中字號大小是變量,因為input 控制項的字號與正文號不同,所以需要單獨設定:

body {
    font-size: var(--font-size);
}

:root {
    --font-size: 16px;
}

.toggle {
    position: absolute;
    font-size: var(--font-size); 
    width: 5em;
    height: 8em;
    margin: 0;
    filter: opacity(0);
    cursor: pointer;
    z-index: 2;
}
登入後複製

設定開關的輪廓:

.switch {
    position: absolute;
    width: 5em;
    height: 8em;
    border-radius: 1.2em;
    background: linear-gradient(#d2d4d6, white);
}
登入後複製

用陰影讓開關變成立體:

.switch {
    box-shadow: 
        inset 0 -0.2em 0.4em rgba(212, 212, 212, 0.75), 
        inset 0 -0.8em 0 0.1em rgba(156, 156, 156, 0.85), 
        0 0 0 0.1em rgba(116, 116, 116, 0.8), 
        0 0.6em 0.6em rgba(41, 41, 41, 0.3), 
        0 0 0 0.4em #d4d7d8;
}
登入後複製

用偽元素設定onoff 文本,目前是處於off 狀態:

.toggle ~ .switch::before,
.toggle ~ .switch::after {
    position: absolute;
    width: 100%;
    text-align: center;
    font-size: 1.4em;
    font-family: sans-serif;
    text-transform: uppercase;
}

.toggle ~ .switch::before {
    content: '|';
    bottom: 1em;
    color: rgba(0, 0, 0, 0.5);
    text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.8);
}

.toggle ~ .switch::after {
    content: 'O';
    top: 0.6em;
    color: rgba(0, 0, 0, 0.45);
    text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.4);
}
登入後複製

input 控制項設定為checked狀態,以便設定處於on 狀態的樣式:

登入後複製

設定處於on 狀態的開關樣式:

.toggle:checked ~ .switch {
    background: linear-gradient(#a1a2a3, #f0f0f0);
    box-shadow: 
        inset 0 0.2em 0.4em rgba(212, 205, 199, 0.75), 
        inset 0 0.8em 0 0.1em rgba(255, 255, 255, 0.77), 
        0 0 0 0.1em rgba(116, 116, 118, 0.8), 
        0 -0.2em 0.2em rgba(41, 41, 41, 0.18), 
        0 0 0 0.4em #d4d7d8;
}
登入後複製

設定處於on 狀態的文字樣式:

.toggle:checked ~ .switch::before {
    bottom: 0.3em;
    text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.5);
}

.toggle:checked ~ .switch::after {
    top: 1.2em;
    text-shadow: 0 0.1em 0 rgba(255, 255, 255, 0.15);
}
登入後複製

接下來設定燈光效果。
先設定處於 off 狀態的黑暗效果:

.toggle ~ .light {
    width: 100vw;
    height: 100vh;
    background-color: #0a0a16;
    z-index: 1;
    filter: opacity(0.7);
}
登入後複製

再設定處於 on 狀態的明亮效果:

.toggle:checked ~ .light {
    filter: opacity(0);
}
登入後複製

大功告成!

以上是如何使用純CSS實現電源開關控制項(附源碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!