前端每日實戰:30# 視頻演示如何用純 CSS 創做一個晃動的公告板

圖片描述

效果預覽

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

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

可交互視頻教程

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

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

https://scrimba.com/c/cD8yKHbgithub

源代碼下載

每日前端實戰系列的所有源代碼請從 github 下載:chrome

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

代碼解讀

定義 dom,容器中包含公告牌、掛公告牌的細繩和固定繩子的 3 個圖釘:flex

<div class="signboard">
    <div class="sign">THANKS</div>
    <div class="strings"></div>
    <div class="pin top"></div>
    <div class="pin left"></div>
    <div class="pin right"></div>
</div>

居中顯示:url

html, body {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: radial-gradient(circle at center 60%, white, sandybrown);
}

定義公告牌的總體尺寸:spa

.signboard {
    width: 400px;
    height: 300px;
}

設置木板的樣式:

.signboard {
    position: relative;
}

.sign {
    width: 100%;
    height: 200px;
    background: burlywood;
    border-radius: 15px;
    position: absolute;
    bottom: 0;
}

設置有雕刻效果的文字樣式:

.sign {
    color: saddlebrown;
    font-family: sans-serif;
    font-weight: bold;
    text-align: center;
    line-height: 200px;
    text-shadow: 0 2px 0 rgba(255, 255, 255, 0.3),
                0 -2px 0 rgba(0, 0, 0, 0.7);
}

畫出細繩:

.strings {
    width: 150px;
    height: 150px;
    border: 5px solid brown;
    position: absolute;
    border-right: none;
    border-bottom: none;
    transform: rotate(45deg);
    top: 38px;
    left: 122px;
}

畫出細繩頂部的圖釘:

.pin {
    width: 25px;
    height: 25px;
    border-radius: 50%;
    position: absolute;
}

.pin.top {
    background: gray;
    left: 187px;
}

畫出木板上左右兩側的圖釘:

.pin.left,
.pin.right {
    background: brown;
    top: 110px;
    box-shadow: 0 2px 0 rgba(255, 255, 255, 0.3);
}

.pin.left {
    left: 80px;
}

.pin.right {
    right: 80px;
}

最後,讓告示牌晃動起來:
(此處已按 小蕾蕾 的建議修改成以頂部圖釘做爲旋轉軸,比最初的效果要好)

.signboard {
    animation: swing 1.5s ease-in-out infinite alternate;
    transform-origin: 200px 13px;
}

@keyframes swing {
    from {
        transform: rotate(10deg);
    }

    to {
        transform: rotate(-10deg);
    }
}

大功告成!

相關文章
相關標籤/搜索