简体   繁体   中英

Get Height of document in React

How do you find the height of the entire document on page load in React? So in jQuery it would look something like:

$(document).height();

Thanks for your help!

I just spent some serious time figuring some things out with React and scrolling events / positions - so for those still looking, here's what I found:

The viewport height can be found by using window.innerHeight or by using document.documentElement.clientHeight . (Current viewport height)

The height of the entire document (body) can be found using window.document.body.offsetHeight .

If you're attempting to find the height of the document and know when you've hit the bottom - here's what I came up with:

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 });
  }
}

(My navbar was 72px in fixed position, thus the -72 to get a better scroll-event trigger)

Lastly, here are a number of scroll commands to console.log(), which helped me figure out my math actively.

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);

Whew! Hope it helps someone!

它的工人对我来说:

document.documentElement.offsetHeight

Finding the height of document on page load is a too tricky, in my opinion! However, finding it after page has loaded is kind of an easier task. Therefore, try to find it in the "componentDidMount()" function! You can either use:

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

(The truth is React also has a built-in version of jQuery, so you can actually use the second way to get the height)

For example:

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()你需要导入

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