window.innerWidth 实时
Posted
技术标签:
【中文标题】window.innerWidth 实时【英文标题】:window.innerWidth in real time 【发布时间】:2019-01-15 13:54:10 【问题描述】:当我实时调整浏览器大小时,我需要获取浏览器的宽度。到目前为止,我找到了一个给出宽度但不是实时的解决方案。只有在我刷新网页后才会更新该值。调整浏览器大小时如何获取值。
我的方法
render()
var windowWidth = window.innerWidth;
return (
<div className="body_clr">
windowWidth
</div>
)
如果我刷新页面,此解决方案有效。但是我想在调整大小时获得宽度,因为我必须以特定的屏幕尺寸执行功能。
【问题讨论】:
简单的答案:不可能。浏览器和js之间没有“实时”。您可以使用事件,但它们在时间上不是真实的。 ***.com/questions/19014250/… 【参考方案1】:这是一种方法:
import React from "react";
import ReactDOM from "react-dom";
class App extends React.Component
constructor()
super();
this.state =
height: 0,
width: 0
;
window.addEventListener("resize", this.update);
componentDidMount()
this.update();
update = () =>
this.setState(
height: window.innerHeight,
width: window.innerWidth
);
;
render()
return (
<React.Fragment>
<p>height: this.state.height</p>
<p>width: this.state.width</p>
</React.Fragment>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
工作代码沙盒here。
【讨论】:
当 vanilla javascript 可以完成这项工作时,你为什么要使用 react? 问题上有一个reactjs
标签,所以我认为它可能会有所帮助。【参考方案2】:
你可以使用event listeners:
window.addEventListener("resize", function()
return window.innerWidth;
);
【讨论】:
以上是关于window.innerWidth 实时的主要内容,如果未能解决你的问题,请参考以下文章
不正确的 window.innerWidth 和 window.innerHeight
WKWebView 的调整大小处理程序中未更新 window.innerWidth/Height
如何让 CSS 媒体查询与 jQuery $(window).innerWidth() 一起使用?