简体   繁体   中英

Using javascript variables based on viewport dimensions to alter CSS properties

Learning javascript currently, cannot get my head around this, or why it's not working.

I'm attempting to use javascript variables based on the viewport dimensions to adjust the size of a div (so the div will expand or shrink specifically for a mobile phone's dimensions, or when you switch from landscape to portrait.)

Currently, in Chrome inspector, it shows the div at 0 0 (top left corner) with dimensions of 0px x 0px. The console.log does provide dimensions of the viewport and advise if it showing as portrait or landscape.

In addition, I can confirm the image is in the directory I've set it to (because at one point I had this working but then I broke the background. Background currently working again).

Here's the javascript so far -

  $(document).ready(function() { //Variables for viewport height and width. var windowWidth = $(window).width(); var windowHeight = $(window).height(); //resizeCloud function alters cloud image size by append cloud ID to include H & W variables function resizeCloud() { $('#cloud').css('width: ',windowWidth + 'px'); $('#cloud').css('height: ',windowHeight + 'px'); $(window).resize(resizeCloud); }; //Will advise if app is in portrait or landscape console.log("width: " + windowWidth); console.log("height: " + windowHeight); if (windowWidth < windowHeight) { console.log("Portrait mode"); } else { console.log("Landscape mode"); }; 

});

And the CSS -

  #cloud { background-image: url('images/cloud.png'); position: absolute; top: 0; left: 0; background-size: contain; 

The HTML is just < div ID='cloud'>< /div> (sans spaces).

If there is an easier way to do this, let me know! Any help greatly appreciated!

You don't need to use JS for that, CSS will do the trick. Just add "width: 100%" to your #cloud, and ensure that the #cloud is relative to a container which spans the full width of the screen.

For the event be bind, you should declare the function resizeCloud and bind it outside.

// Declare function
function resizeCloud() {
    $('#cloud').css('width', windowWidth + 'px');
    $('#cloud').css('height', windowHeight + 'px');
};

$(window).resize(resizeCloud); // Bind event

Also, pay attention to arguments of css method: http://api.jquery.com/css/

Anyway, you're trying use javascript for a CSS solution.

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