简体   繁体   中英

jQuery - set div height equal to div width

I'm trying to make a responsive website that has a grid of squares. So I need the height of each div (with a class of 'main') to be the same as the div width when it resizes. I'm quite new to jQuery so I was hoping somebody could tell me what I'm doing wrong here.

var divWidth = $('.main').width(); 

$(window).resize(function(){
    $('.main').height() = divWidth;
});

Many thanks!

You should not declare the divWidth outside the scope of the resize() function, because the value will not be updated when the resize event is fired. Also, there is a risk that there may be multiple .main elements. Either use an ID, or loop through all classes (if there are multiple instances).

Try this:

$(window).resize(function(){
    // If there are multiple elements with the same class, "main"
    $('.main').each(function() {
        $(this).height($(this).width());
    });

    // Or you can switch to using an ID
    $('#main').height($('#main').width());
}).resize();

You fire the resize() event again to ensure that the size is set upon loading.

You can do:

var divWidth = $('.main').width(); 

$(window).resize(function(){
    $('.main').height(divWidth);
});

Try

var divWidth = $('.main').width(); 

$(window).resize(function(){
    $('.main').height(divWidth);
});

Try this:

var divWidth = $('.main').width(); 

$(window).resize(function(){
    $('.main').height( divWidth );
});

Note that the height() will give you the height when calling with no arguments, but with an argument, it will change the height of the object ;)

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