简体   繁体   中英

ScrollY addclass after 100vh

I am working on a reactjs project and was wondering how I would be able to change ScrollY px values to something like vh .

state = {
  isTop: true,
};

componentDidMount() {
  document.addEventListener('scroll', () => {
    const isTop = window.scrollY < 100;
    if (isTop !== this.state.isTop) {
        this.setState({ isTop })
    }
  });
}

Where I am adding/removing class:

<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
  <NavLink href="/">Logos</NavLink>
</NavItem>

Right now I add a class after 100px. But, is it possible to add the class after you scroll through 100vh or the viewport height?

window.outerHeight is what you are looking for if you run into this issue.

Solution:

constructor(props) {
  super(props);

  this.state = {
    width: 0, 
    height: 0
  };
  this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}

state = {
  isTop: true,
};

componentDidMount() {
  this.updateWindowDimensions();
  window.addEventListener('resize', this.updateWindowDimensions);
  document.addEventListener('scroll', () => {
    const isTop = window.scrollY < window.innerHeight;
    if (isTop !== this.state.isTop) {
        this.setState({ isTop })
    }
  });
}

componentWillUnmount() {
  window.removeEventListener('resize', this.updateWindowDimensions);
}

updateWindowDimensions() {
  this.setState({ width: window.innerWidth, height: window.innerHeight });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM