javascript - ReactJS 改变滚动元素的颜色以及到达特定位置时的颜色

标签 javascript css reactjs

是否可以更改标题的类,以便在背景更改时更改其颜色?我有一个标题和一些部分。标题是固定的,当它到达具有不同背景颜色的部分时,我想更改标题颜色以获得更好的可读性,但我不知道该怎么做。我已经在网上搜索了它,但我无法找到任何东西。

这是我目前得到的:(参见 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/

相关文章:

reactjs - 从输入中获取数字时,React 计数器不会增加

javascript - 在 Ruby on Rails 项目中使用 Particle.js

javascript - jQuery 代码在 Safari 中工作,但一半在 IE 中工作

javascript - Object.hasOwnProperty 与 Object.prototype.hasOwnProperty 的实际区别

html - 如何使用静态占位符自动缩放输入?

javascript - Express.js,意外的 token <

reactjs - React 样板中的服务器端渲染

javascript - 如何在日期选择器中的 JQUERY 中设置从当前日期开始的 -3 年和从当前日期开始的 +9 个月

css - 使用 flexbox(...或不使用 flexbox)的高级居中

javascript - 添加滑动功能以隐藏 HTML 菜单