简体   繁体   中英

Jquery doesn't change div's width on smaller screen after auto adjusting on regular screen

Got the script that auto adjusts width of children divs depending on the number of children. And on smaller screen i need them to be 100% wide. I've tried inserting the script right into the script that adjusts width on regular screen. Doesn't work. Also tried inserting it in the very bottom of the page. Didn't work too.

Here is the code

$(".basecollections").each(function(){
var child_width = 100 / $(this).children().length;
    child_width = Math.floor(child_width);
$(this).children().css("width", child_width + "%");
     if ( screen.width < 1000 ) {
    $(this).children().css('width','100%');
  } 
})

http://jsfiddle.net/3x466nb1/

instead of screen.width you need to use $(window).width() : DEMO

$(".basecollections").each(function(){
    var child_width = 100 / $(this).children().length;
    child_width = Math.floor(child_width);
    $(this).children().css("width", child_width + "%");
    if ( $(window).width() < 1000 ) {
        $(this).children().css('width','100%');
    } 
});

also if you want the change to be dynamic, you need to write this piece of code inside the resize event of the window element:

$(window).resize(function(){
    $(".basecollections").each(function(){
        var child_width = 100 / $(this).children().length;
        child_width = Math.floor(child_width);
        $(this).children().css("width", child_width + "%");
        if ( $(window).width() < 1000 ) {
            $(this).children().css('width','100%');
        } 
    });
});

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