是否可以更改标题的类,以便在背景更改时更改其颜色?我有一个标题和一些部分。标题是固定的,当它到达具有不同背景颜色的部分时,我想更改标题颜色以获得更好的可读性,但我不知道该怎么做。我已经在网上搜索了它,但我无法找到任何东西。
这是我目前得到的:(参见 JSFIDDLE)
class Div extends React.Component{
constructor() {
super()
this.state = {
headerClass: 'white'
}
}
changeColor() {
// something like
this.setState({ headerClass: 'black'})
}
render(){
return(
<div>
<div id="header">
<h1 className={`${this.state.headerClass}`}>
This is the header
</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_3" className="section">
This is section 3
</div>
<div id="section_4" className="section">
This is section 4
</div>
<div id="section_5" className="section">
This is section 5
</div>
</div>
)
}
}
CSS:
#main {
height: 2000px;
position: relative;
}
#section_1 {
background: grey;
}
.section {
height: 400px;
background: white;
padding: 30px 0;
}
#header {
height: 50px;
background: transparent;
position: fixed;
width: 100%;
left: 0;
top: 0;
right: 0;
z-index: 1
}
h1 {
color: white;
}
那么,有什么提示吗?
最佳答案
试试这个:
import React from 'react'
export default class Div extends React.Component{
state = {
color: 'white'
}
listenScrollEvent = e => {
if (window.scrollY > 400) {
this.setState({color: 'black'})
} else {
this.setState({color: 'white'})
}
}
componentDidMount() {
window.addEventListener('scroll', this.listenScrollEvent)
}
render() {
return(
<div>
<div id="header">
<h1 style={{color: this.state.color}}>
This is the header
</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_3" className="section">
This is section 3
</div>
<div id="section_4" className="section">
This is section 4
</div>
<div id="section_5" className="section">
This is section 5
</div>
</div>
)
}
}
基本上我们只是使用 window.scrollY
来了解用户滚动到了哪里。
关于javascript - ReactJS 改变滚动元素的颜色以及到达特定位置时的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48458832/