【问题标题】:Get Height of document in React在 React 中获取文档的高度
【发布时间】:2017-09-20 14:37:36
【问题描述】:

如何在 React 中找到页面加载时整个文档的高度?所以在 jQuery 中它看起来像:

$(document).height();

感谢您的帮助!

【问题讨论】:

  • document.documentElement.offsetHeight
  • React 不是一个 DOM 实用程序库,它不为此提供任何功能。你得到高度的方式与没有 React 的方式完全相同。

标签: reactjs dom ecmascript-6 components jsx


【解决方案1】:

我刚刚花了一些时间用 React 和滚动事件/位置来解决一些问题 - 所以对于那些仍在寻找的人,这就是我发现的:

可以使用window.innerHeightdocument.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);

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

【讨论】:

  • 感谢您回答这个问题!我只是做了一些格式更改,希望它们是一种改进。如果是这样,您可以单击edit 按钮查看我用来实现这种格式的源代码,以便您在以后的帖子中使用它。干杯!
  • 谢谢。我一定会在未来包括反引号。绝对读起来更好。
【解决方案2】:

我的工人:

document.documentElement.offsetHeight

【讨论】:

    【解决方案3】:

    在我看来,在页面加载时查找文档的高度太棘手了! 但是,在页面加载后找到它是一项更容易的任务。 因此,尝试在“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() 时,我得到 $ 没有定义。
    【解决方案4】:

    要在 React 中使用 $(document).height(),您需要导入

    【讨论】:

    • 欢迎来到 SO。你能证明它是如何解决答案本身的问题的吗?
    猜你喜欢
    • 2015-11-15
    • 2013-03-22
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 2023-04-02
    相关资源
    最近更新 更多