簡體   English   中英

在 React 中獲取文檔的高度

[英]Get Height of document in React

你如何在 React 頁面加載時找到整個文檔的高度? 所以在 jQuery 中它看起來像:

$(document).height();

謝謝你的幫助!

我只是花了一些時間用 React 和滾動事件/位置來解決一些問題 - 所以對於那些仍在尋找的人,這是我發現的:

可以使用window.innerHeight或使用document.documentElement.clientHeight找到視口高度。 (當前視口高度)

可以使用window.document.body.offsetHeight找到整個文檔(正文)的高度。

如果您試圖找到文檔的高度並知道何時到達底部 - 這就是我想出的:

if (window.pageYOffset >= this.myRefII.current.clientHeight &&
  Math.round((document.documentElement.scrollTop + window.innerHeight))
  < document.documentElement.scrollHeight - 72) {
    this.setState({ trueOrNot: true });
  } else {
    this.setState({ trueOrNot: false });
  }
}

(我的導航欄在固定位置是 72px,因此 -72 以獲得更好的滾動事件觸發器)

最后,這里有一些 console.log() 的滾動命令,它們幫助我積極地計算出我的數學。

console.log('window inner height: ', window.innerHeight);

console.log('document Element client hieght: ', document.documentElement.clientHeight);

console.log('document Element scroll hieght: ', document.documentElement.scrollHeight);

console.log('document Element offset height: ', document.documentElement.offsetHeight);

console.log('document element scrolltop: ', document.documentElement.scrollTop);

console.log('window page Y Offset: ', window.pageYOffset);

console.log('window document body offsetheight: ', window.document.body.offsetHeight);

哇! 希望它可以幫助某人!

它的工人對我來說:

document.documentElement.offsetHeight

在我看來,在頁面加載時找到文檔的高度太棘手了! 但是,在頁面加載后找到它是一種更容易的任務。 因此,嘗試在“componentDidMount()”函數中找到它! 您可以使用:

  • document.documentElement.offsetHeight
  • $(document).height()

(事實是 React 也有內置版本的 jQuery,所以你實際上可以使用第二種方式來獲取高度)

例如:

import React, {Component} from 'react';

export default class YourClass extends Component {
    constructor(props){
        super(props);
        // ...
    }

    componentDidMount() {
        console.log("document-height",document.documentElement.offsetHeight);
        console.log("jQuery-document-height",$(document).height());
    }

    render(){
        // ...
    }

}

要在 React 中使用$(document).height()你需要導入

暫無
暫無

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

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