前端每日實戰:9# 視頻演示如何用純 CSS 創做一種按鈕被瞄準的交互特效

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕在當前頁面預覽,點擊連接全屏預覽。css

https://codepen.io/zhang-ou/pen/ELWMLrhtml

可交互視頻教程

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。git

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

https://scrimba.com/c/cqrNEsmchrome

源代碼下載

請從 github 下載。dom

https://github.com/comehope/front-end-daily-challenges/tree/master/009-aimed-button-effectsflex

代碼解讀

定義 dom,容器中包含 5 個 span,第 1 個是按鈕文字,另 4 個用來修飾:動畫

<div class="box">
    <span>BUTTON</span>
    <span class="top"></span>
    <span class="bottom"></span>
    <span class="left"></span>
    <span class="right"></span>
</div>

居中顯示:spa

html, body {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
    color: silver;
}

設置文字樣式:code

.box {
    width: 9em;
    height: 3em;
    font-size: 30px;
    text-align: center;
    line-height: 3em;
    letter-spacing: 0.2em;
    font-family: sans-serif;
}

畫出瞄準鏡中間的圓圈:

.box {
    position: relative;
}

.box::after {
    content: '';
    position: absolute;
    width: 3em;
    height: 3em;
    border: 1px solid red;
    border-radius: 50%;
    left: 3em;
}

畫出瞄準鏡的十字座標線:

.box span:not(:first-child) {
    position: absolute;
    background-color: red;
}

.box span.top,
.box span.bottom {
    width: 1px;
    height: 3em;
    left: 50%;
}

.box span.top {
    top: -3em;
}

.box span.bottom {
    bottom: -3em;
}

.box span.left,
.box span.right {
    width: 3em;
    height: 1px;
    top: 50%;
}

.box span.left {
    left: 0;
}

.box span.right {
    right: 0;
}

定義瞄準動畫:

@keyframes aim {
    from {
        filter: opacity(0.2);
    }

    to {
        filter: opacity(0.8);
    }
}

應用瞄準動畫到瞄準鏡上:

.box::after {
    filter: opacity(0);
}

.box span:not(:first-child) {
    filter: opacity(0);
}

.box:hover::after,
.box:hover span:not(:first-child) {
    animation: aim 1s linear infinite alternate;
}

最後,爲容器設置從模糊到清晰的緩動效果:

.box {
    filter: blur(2px);
    transition: 0.5s;
}

.box:hover {
    filter: blur(0.2px);
}

大功告成!

知識點

相關文章
相關標籤/搜索