效果展示
可以看到文字随着屏幕滑动条的滚动逐渐渐入渐出
接下来看看我是怎么实现的把
实现原理
要实现这个效果也很简单,就是利用background-image属性的linear-gradient给文字加上渐变背景,然后设置background-clip: text,只保留文字区域背景,然后设置文字颜色透明,这样文字就有静态的渐变效果。
但是要实现滚动时渐变,就要利用到JS了,JS部分也很简单,通过监听document对象的scroll事件,然后设置background-position-x属性控制渐变背景偏移,就搞定了
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文字渐入特效</title>
<style>
html {
font-size: 10px;
}
* {
margin: 0;
padding: 0;
}
body {
display: flex;
height: 300vh;
background-color: #000000;
}
.sticky {
position: sticky;
top: 0;
display: flex;
width: 100vw;
height: 100vh;
justify-content: center;
align-items: center;
}
h1 {
color: transparent;
font-size: 5rem;
font-family: "Helvetica Neue", Helvetica, Arial;
background-image: linear-gradient(75deg, #fff 0%, #ffffff 33.33%, rgba(255, 255, 255, 0) 66.67%, rgba(255, 255, 255, 0) 100%);
background-size: 300% 100%;
background-position-x: 100%;
background-clip: text;
-webkit-background-clip: text;
}
h1:hover{
background-position-x: 0;
}
</style>
</head>
<body>
<div class="sticky"><h1>Less bazel, more screen.</h1></div>
</body>
<script>
const h1=document.querySelector('h1')
document.addEventListener('scroll',()=>{
let scrolled=document.documentElement.scrollTop/(document.documentElement.scrollHeight-
document.documentElement.clientHeight)
console.log(scrolled)
h1.style.backgroundPositionX=`${(1-scrolled)*100}%`
})
</script>
</html>