簡體   English   中英

滾動時更改div的高度

[英]Changing height of a div on scrolling

我正在使用reactjs做一個Web應用程序。 而且,我需要在向下滾動時更改div的高度,並在向上滾動時恢復到原始高度。 我不確定是否有我需要的僅CSS解決方案。 實現上述目標的方式是什么?

class InternalGroupsPage extends Component {
     constructor() {
     super();
}

render() {

return (
         <div className="body_clr">

            <div className="group_page_header">
                    This is the div i want to change the height when scrolling
            </div>

            <div>
                    Other stuff
            </div>
         </div>

        );
    }
}

的CSS

.group_page_header {

    width: 100%;
    height: 220px;
    background-color: #0b97c4;
    position: fixed;
    margin-top: 50px;
    z-index: 1;

}

.body_clr {

    overflow-y: scroll;
    width: 100%;
    height: 100%;
    position: fixed;
    background-color: #eceff1;

}

因此,基本上就像我在評論中提到的那樣。

基本上,當scrollTop通過某個點以進行重新渲染時,您需要切換狀態變量+ className。

這是手柄滾動功能:

handleScroll(event) {
      var scrollTop = event.srcElement.body.scrollTop;
      var isScrollUp = this.getScrollDirection();

      if(isScrollUp) {
        this.setState({
          hideHeader: true,
        });
      } else {
        this.setState({
          hideHeader: false,
        });
      }
  };

要檢測滾動方向:

getScrollDirection() {
    var currentScrollTop = document.body.scrollTop;
    var isScrollUp = currentScrollTop < this.previousScrollTop;
    this.previousScrollTop = currentScrollTop;
    return isScrollUp;
  }

和render函數來切換類

 render() {
    var headerClassName = this.state.hideHeader ? `group_page_header hideHeader` : `group_page_header showHeader`;
    console.log('classNAme ->', headerClassName)
    return (
      <div className="body_clr">
        <div className={headerClassName}>
        This is the div i want to change the height when scrolling
        </div>
        <div className="other-stuff">
          Other stuff
        </div>
      </div>
    );
  }

這是小提琴

您可以更新小的CSS更改並嘗試一下。 基本上,這應該是您達到此要求所應遵循的方向。

使用JQuery:

$('.body_clr').scroll( function() {

    var topPos = $(this).scrollTop();

    var calcheight = 0; // use this variable to calculate the height of the div based on topPos

    $('.group_page_header').height( calcheight );

})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM