简体   繁体   English

使用react滚动时如何更改永久项的css

[英]how to change css of permanent item when scroll using react

how can I change div's height on scroll while i'm using react??? 我在使用react时如何更改div的滚动高度?

<div id="navigation"></div>

css: CSS:

#navigation{
  background: #fff;
  position: fixed;
  width:100%;
  height:60px;
  text-align: center;
  direction: rtl;
}

You can use plain Javascript, with event listeners. 您可以使用带有事件侦听器的纯Javascript。 Change the state based on how far was scrolled and toggle a class. 根据滚动的距离更改状态并切换类。 Here's an example: 这是一个例子:

 class Example extends React.Component { constructor() { super(); this.state = { hasScrolled: false, }; this.handleScroll = this.handleScroll.bind(this); } handleScroll() { let hasScrolled = true; // Check if it was scrolled back to the top. if (document.body.scrollTop <= 20) { hasScrolled = false; } this.setState({ hasScrolled }); } componentDidMount() { // Listen on scrolling event, call our function. window.addEventListener('scroll', this.handleScroll); } componentWillUnmount() { // Unlisten if the component unmounts. window.removeEventListener('scroll', this.handleScroll); } render() { // Add className to the navigation based on our state. return ( <div> <div id="navigation" className={this.state.hasScrolled ? 'onscroll' : null} /> <p> Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. </p> </div> ); } } ReactDOM.render(<Example />, document.getElementById('root')); 
 #navigation { background: red; position: fixed; top: 0; width: 100%; height: 60px; text-align: center; direction: rtl; transition: .2s ease height; } #navigation.onscroll { height: 30px; } p { margin: 80px 20px; font-size: 34px; font-family: system-ui, sans-serif; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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