[英]How Do I Get Browser Viewport Width & Height In Javascript And Apply To CSS ID's?
Is there a way to get the realtime width
and height
values using Javascript and apply them to a number of div id
's? 有没有一种方法可以使用Javascript获得实时的
width
和height
值,并将其应用于多个div id
? I want to build a site that has 5 sections that are always width: 100vw
and height: 100vh
. 我想建立一个站点,该站点具有5个部分,这些部分的
width: 100vw
始终width: 100vw
, height: 100vh
始终width: 100vw
height: 100vh
。 Only one section can be seen at a time as each section has a #
anchor and vertical scrolling is disabled. 一次只能看到一个部分,因为每个部分都有一个
#
锚点,并且垂直滚动被禁用。
The problem I'm having is when I resize the browser window, the CSS doesn't keep up and must be refreshed for new values for the section width
and height
. 我遇到的问题是,当我调整浏览器窗口的大小时,CSS无法跟上,必须刷新以获取部分
width
和height
新值。 I'm wondering if there is a way for Javascript to constantly monitor the browser width
and height
and apply those values to a set of id
's. 我想知道Javascript是否有一种方法可以不断监视浏览器的
width
和height
并将这些值应用于一组id
。
Example 例
The browser window is 1000px by 500px so the id #one, #two
now have a width: 1000px
and height: 500px
and when the browser is resized to 1200px by 600px the values for #one , #two
would be set as width: 1200px
and height: 600px
in the CSS. 浏览器窗口的大小为
id #one, #two
x 500px,因此id #one, #two
现在的width: 1000px
id #one, #two
height: 500px
,将浏览器的大小调整为1200px x 600px时#one , #two
的值将设置为width: 1200px
和height: 600px
CSS中为height: 600px
。
As @gary-storey already said, use the resize event: 正如@ gary-storey已经说过的,请使用resize事件:
$(window).resize(function() {
var curWinWidth = $(window).width();
var curWinHeight = $(window).height();
// do stuff here
});
i've done this for my own page, that way: 我已经在自己的页面上完成了此操作:
$(window).resize(function() {
<!-- get viewport size//set content size -->
var currentViewPortHeight = $( window ).height();
var currentViewPortWidth = $( window ).width();
$("#mainFrame").css({ "height" : currentViewPortHeight, "width" : currentViewPortWidth });
$("#mainFrame").resize();
};
you may set a timeout interval though - since this event fires very often during a windo resize - especially if the user uses drag&drop. 不过,您可以设置超时间隔-因为此事件在窗口大小调整期间经常触发-特别是在用户使用拖放操作时。 according to my stackoverflow studies, the best would be a 300ms timeout, to get a smooth resize transition, and not firing it to often...
根据我的stackoverflow研究,最好是300ms的超时时间,以实现平滑的调整大小过渡,而不是频繁触发...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.