前端相較於後端等領域,能夠在短時間內擁有可視化的成果,對於剛起步的小夥伴而言,這是不斷努力學習提高的巨大動力,本篇博客拋磚引玉,利用HTML+CSS實現彩虹文字以及聚光燈動畫效果,首先向大家介紹應用的CSS的主要屬性
- background-clip
:
Thebackground-clip
CSS property sets whether an element's background extends underneath its border box, padding box, or content box. - clip-path
:
Theclip-path
CSS property creates a clipping region that sets what part of an element should be shown. Parts that are inside the region are shown, while those outside are hidden.
上述爲background-clip屬性和clip-path屬性在MDN上的定義,總結來看,background-clip設置元素的背景是否擴展到其邊框框、填充框或內容框之下,各個不同的屬性值具體表現如下圖所示,其中,本博客實現彩虹文字特效的方案利用background-clip:text實現,而clip-path屬性則會創建一個剪切區域,用於設置元素應該顯示的部分。區域內的部分顯示出來,而區域外的部分則隱藏起來。
有了上述兩個屬性,我們可以輕鬆實現類似下面視頻中的聚光燈效果,核心思路爲,利用絕對定位不佔位置的特點,重疊的設置兩個盒子,並在將上層盒子的內容設置爲彩虹文字,並且上層盒子的內容利用clip-path屬性部分顯示,具體源碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>聚光燈</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #222;
}
h1 {
position: relative;
color: #333333;
font-size: 8rem;
}
h1::after {
position: absolute;
left: 0;
top: 0;
content: "聚光燈";
background: -webkit-linear-gradient(left, #c23636, #192a56, #00d2d3, yellow, #6d2a4f, #2e86de, #4cd137, #e84118);
-webkit-background-clip: text;
color: transparent;
-webkit-clip-path: circle(100px at 0% 50%);
animation: light linear 4s infinite alternate;
}
@keyframes light {
0% {
-webkit-clip-path: circle(100px at 0% 50%);
}
50% {
-webkit-clip-path: circle(100px at 50% 50%);
}
100% {
-webkit-clip-path: circle(100px at 100% 50%);
}
}
</style>
</head>
<body>
<h1>聚光燈</h1>
</body>
</html>
本系列博客會陸續更新,主要內容爲所前端學習過程中的心得體會,如感興趣,大家多關注鼓勵