简体   繁体   中英

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? I want to build a site that has 5 sections that are always width: 100vw and 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 . 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.

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.

Here is my codepen .

As @gary-storey already said, use the resize event:

$(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...

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