[英]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.