将文本随背景更改为新颜色,如 Parallex 背景



我正在开发一个具有固定标头的Web应用程序。 标题具有绿色背景和白色文本。我希望它做的是在用户向下滚动时将视差更改为带有黑色文本的白色背景。

我可以获取背景来执行此操作,例如使用两个具有不同背景(一个绿色和一个白色(和 z 索引的叠加div,一个位于正常定位的顶部,另一个固定。示例代码:

.white-bg {
width: calc(100% - 1rem);
height: 80px;
background-color: white;
position: fixed;
top: 0px;
z-index: 1;
}
.green-bg {
width: 100%;
height: 80px;
position: absolute;
top: 0px;
background-color: green;
z-index: 2;
}
.menu-bar {
height: 80px;
width: 100%;
position: fixed;
top: 0px;
z-index: 3;
}

但是我无法让文本同时从白色变为黑色,显然我无法使其透明或使用与背景相同的技术。

建议?

我将检查滚动事件并更改标头类:

document.addEventListener("scroll", (e) => {
if (window.scrollY > 0) {
header.classList.add("active");
} else {
header.classList.remove("active");
}
});

POC:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
h1 {
font-size: 48px;
font-weight: 800;
color: green;
margin: 0;
cursor: pointer;
}
body {
background: lightblue;
}
</style>
</head>
<body>
<h1 onclick="doIt()">Hello World</h1>
</body>
<script>
function doIt() {
let i = 0;
const x = setInterval(() => {
document.querySelector("h1").style = `background: -webkit-linear-gradient(90deg, white, green ${i}%);
background-clip: text;
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;`;
i += 10;
if (i > 2000) {
clearInterval(x);
document.querySelector("h1").style = 'color: white;';
}
}, 15);
}
</script>
</html>