是否有任何方法可以通过React中滚动的fade动画来实现更改背景颜色?我可以在卷轴上实现背景变化效果,但无法添加渐变效果。
import React from "react";
export default class ScrollBackground extends React.Component {
state = {
bgcolor: "black",
color: "white",
};
listenScrollEvent = (e) => {
if (window.scrollY < 5300) {
return this.setState({
bgcolor: "black",
color: "white",
opacity: 1 - window.scrollY / 5300,
});
} else {
return this.setState({ bgcolor: "white", color: "black", opacity: 0 });
}
};
componentDidMount() {
window.addEventListener("scroll", this.listenScrollEvent);
}
render() {
return (
<div
style={{
background: this.state.bgcolor,
color: this.state.color,
height: "800px",
}}
>
<div id="header">
<h1>fsefd</h1>
</div>
<div id="section_1" className="section">
This is section 1
</div>
<div id="section_2" className="section">
This is section 2
</div>
<div id="section_5" className="section">
This is section 5
</div>
</div>
);
}
}
您需要使用CSS转换,例如:transition: "background-color 0.5s ease"
。以创建渐变效果。
CSS转换提供了一种在更改CSS属性时控制动画速度的方法。您可以使属性的更改在一段时间内发生,而不是立即生效。
例如,如果将元素的颜色从白色更改为黑色,通常变化是瞬间的。使用CSS转换启用后,在加速后的时间间隔内发生更改曲线,所有这些都可以自定义。
另外,不要忘记使用去抖动演示:
const { debounce } = _;
const { Component } = React;
class App extends Component {
state = {
bgcolor: "black",
color: "white",
};
listenScrollEvent = debounce((e) => {
if (window.scrollY < 400) {
return this.setState({
bgcolor: "black",
color: "white",
opacity: 1 - window.scrollY / 5300,
});
} else {
return this.setState({ bgcolor: "white", color: "black", opacity: 0 });
}
}, 50);
componentDidMount() {
window.addEventListener("scroll", this.listenScrollEvent);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.listenScrollEvent);
}
render() {
return (
<div
style={{
background: this.state.bgcolor,
transition: "background-color 0.5s ease",
color: this.state.color,
height: 1000,
}}
>
<div id="header">
<h1>fsefd</h1>
</div>
<div id="section_1" className="section">
This is section 1
</div>
<div id="section_2" className="section">
This is section 2
</div>
<div id="section_5" className="section">
This is section 5
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.body)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>