前端每日實戰:12# 視頻演示如何用純 CSS 創做一種文字斷開的交互特效

圖片描述

效果預覽

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

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

可交互視頻教程

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

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

https://scrimba.com/c/c2EvWHNchrome

源代碼下載

請從 github 下載。dom

https://github.com/comehope/front-end-daily-challenges/tree/master/012-broken-text-effects字體

代碼解讀

定義 dom,只有一個元素,元素有一個 data-text 屬性,屬性值等於元素內的文本:flex

<div class="text" data-text="BREAK">BREAK</div>

居中顯示:spa

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

設置漸變背景色:code

body {
    background: linear-gradient(brown, sandybrown);
}

設置文本的字體字號:

.text {
    font-size: 5em;
    font-family: "arial black";
}

利用僞元素增長文字:

.text {
    position: relative;
}

.text::before,
.text::after {
    content: attr(data-text);
    position: absolute;
    top: 0;
    left: 0;
    color: lightyellow;
}

設置左側文字的遮罩:

.text::before {
    background-color: darkgreen;
    clip-path: polygon(0 0, 60% 0, 30% 100%, 0 100%);
}

設置右側文字的背景和遮罩:

.text::after {
    background-color: darkblue;
    clip-path: polygon(60% 0, 100% 0, 100% 100%, 30% 100%);
}

當鼠標劃過期,遮罩的文字分別向兩側偏移:

.text::before,
.text::after {
    transition: 0.2s;
}

.text:hover::before {
    left: -0.15em;
}

.text:hover::after {
    left: 0.15em;
}

隱藏輔助元素,包括原始文字和僞元素的背景色:

.text {
    color: transparent;
}

.text::before {
    /*background-color: darkgreen;*/
}

.text::after {
    /*background-color: darkblue;*/
}

兩側文字增長歪斜效果:

.text:hover::before {
    transform: rotate(-5deg);
}

.text:hover::after {
    transform: rotate(5deg);
}

微調文字的高度:

.text:hover::before {
    top: -0.05em;
}

.text:hover::after {
    top: 0.05em;
}

大功告成!

知識點

相關文章
相關標籤/搜索