前端每日實戰:145# 視頻演示如何用純 CSS 創作一個電源開關控件

圖片描述

效果預覽

按下右側的“點擊預覽”按鈕可以在當前頁面預覽,點擊鏈接可以全屏預覽。

https://codepen.io/comehope/pen/PdMyJd

可交互視頻

此視頻是可以交互的,你可以隨時暫停視頻,編輯視頻中的代碼。

請用 chrome, safari, edge 打開觀看。

[]()

源代碼下載

每日前端實戰系列的全部源代碼請從 github 下載:

https://github.com/comehope/front-end-daily-challenges

代碼解讀

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

<input type="checkbox" class="toggle">
<div class="switch"></div>
<div class="light"></div>

居中顯示:

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 狀態的樣式:

<input type="checkbox" checked="checked" class="toggle">

設置處於 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);
}

大功告成!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章