html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CodePen - Animated Highlight</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="first">占位1</div>
<div class="sticky">
<h1>Less bezel, more screen.</h1>
</div>
<div class="sticky2">
<h1>Less bezel, more screen2.</h1>
</div>
<div class="first">占位2</div>
<div class="sticky3">
<h1>Less bezel, more screen3.</h1>
</div>
<script src="./index.js"></script>
</body>
</html>
css
:root {
--percentage: 0%;
}
body {
background-color: #000;
margin: 0;
height: 450vh;
}
.sticky {
/* position: sticky;
top: 0; */
height: 80vh;
display: flex;
justify-content: center;
align-items: start;
}
.sticky2 {
/* position: sticky;
top: 0; */
height: 60vh;
display: flex;
justify-content: center;
align-items: start;
}
.sticky3 {
/* position: sticky;
top: 0; */
height: 60vh;
display: flex;
justify-content: center;
align-items: start;
}
h1 {
font-family: Helvetica;
margin: 0;
padding: 0;
font-size: 48px;
color: #fff;
letter-spacing: -0.3px;
background-image: linear-gradient(75deg, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 1) 33.33%, rgba(255, 255, 255, 0) 66.67%, rgba(255, 255, 255, 0) 100%);
background-size: 300% 100%;
background-position-x: calc(100% - var(--percentage));
background-clip: text;
-webkit-background-clip: text;
color: transparent;
}
.first{
width: 100%;
height: 500px;
background-color: darkcyan;
}
js
const h1Arr = document.querySelectorAll('h1')
// 只获取第一个first元素
const first = document.querySelector('.first')
document.addEventListener('scroll', e => {
let scrolled
h1Arr.forEach((h1, index) => {
if (index === 0) {
// 滚动完整个占位1这个盒子 scrolled为1
scrolled = document.documentElement.scrollTop / first.scrollHeight
} else {
// 获取 h1的父元素的上一个兄弟元素
let previousEle = h1Arr[index].parentElement.previousElementSibling
scrolled = (document.documentElement.scrollTop - previousEle.offsetTop) / previousEle.scrollHeight
}
if (scrolled > 1) scrolled = 1
if (scrolled < 0) scrolled = 0
h1.style.setProperty('--percentage', `${scrolled * 100}%`)
})
})
参考代码