1. 程式人生 > >如何用純 CSS 創作一個懸停時右移的按鈕特效

如何用純 CSS 創作一個懸停時右移的按鈕特效

在這裡插入圖片描述

效果預覽

線上演示

按下右側的“點選預覽”按鈕可以在當前頁面預覽,點選連結可以全屏預覽。

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

可互動視訊

此視訊是可以互動的,你可以隨時暫停視訊,編輯視訊中的程式碼。

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

https://scrimba.com/p/pEgDAM/cJBwwHn

原始碼下載

本地下載

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

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

程式碼解讀

定義 dom,容器中包含 9 個元素:


<div class="container">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

居中顯示:


body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: black;
}

定義容器尺寸:


.container {
    width: 30em;
    height: 30em;
    font-size: 10px;
}

用 grid 佈局把 9 個子元素排列成 3 * 3 的網格狀:


.container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
}

設定容器內子元素的樣式,是通過偽元素來設定的:


.container span {
    position: relative;
}

.container span::before,
.container span::after 
{
    content: '';
    position: absolute;
    box-sizing: border-box;
    border-style: none solid solid none;
    border-width: 1em;
    border-color: gold;
    width: 100%;
    height: 100%;
}

旋轉容器,讓它的尖端朝上:


.container {
    transform: rotate(-135deg);
}

增加子元素尺寸由小到大變化的動畫:


.container span::before,
.container span::after 
{
    animation: 
        animate-scale 1.6s linear infinite;
}

@keyframes animate-scale {
    from {
        width: 1%;
        height: 1%;
    }

    to {
        width: 100%;
        height: 100%;
    }
}

增加子元素邊框色變化的動畫:


.container span::before,
.container span::after 
{
    animation: 
        animate-border-color 1.6s linear infinite,
        animate-scale 1.6s linear infinite;
}

@keyframes animate-border-color {
    0%, 25% {
        border-color: tomato;
    }

    50%, 75% {
        border-color: gold;
    }

    100% {
        border-color: black;
    }
}

增加子元素邊框寬度變化的動畫:


.container span::before,
.container span::after 
{
    animation: 
        animate-border-width 1.6s linear infinite,
        animate-border-color 1.6s linear infinite,
        animate-scale 1.6s linear infinite;
}

最後,讓 ::after 偽元素的動畫時間慢半拍:


.container span::after {
    animation-delay: -0.8s;
}

@keyframes animate-border-width {
    0%, 100%{
        border-width: 0.1em;
    }

    25% {
        border-width: 1.5em;
    }
}

大功告成!

原文地址:https://segmentfault.com/a/1190000016419507