How to make fluid with jQuery Isotope?

2020-08-01 05:29发布

问题:

I'm trying to make this demo fluid (change img size when window resize) with jQuery Isotope plugin, follow this doc.
Did I do something wrong with my code?
Why is the window.resize seems not working? and use doc smartresize method neither.

Any suggestion will be appreciated, Thanks

jsfiddle demo

HTML CSS

<div id="container">
    <div class="item"><img src="http://placekitten.com/300/350" /></div>
    <div class="item"><img src="http://placekitten.com/300/300" /></div>
    <div class="item"><img src="http://placekitten.com/300/450" /></div>
    <div class="item"><img src="http://placekitten.com/300/200" /></div>
    <div class="item"><img src="http://placekitten.com/300/250" /></div>
    <div class="item"><img src="http://placekitten.com/300/400" /></div>
    <div class="item"><img src="http://placekitten.com/300/200" /></div>
    <div class="item"><img src="http://placekitten.com/300/350" /></div>
    <div class="item"><img src="http://placekitten.com/300/300" /></div>
    <div class="item"><img src="http://placekitten.com/300/450" /></div>
    <div class="item"><img src="http://placekitten.com/300/200" /></div>
    <div class="item"><img src="http://placekitten.com/300/250" /></div>
    <div class="item"><img src="http://placekitten.com/300/400" /></div>
    <div class="item"><img src="http://placekitten.com/300/200" /></div>
</div>​

#container {
    background: black;
}
.item {
    width: 33px;
    float: left;
}
.item img {
    display: block;
    width: 33px;
}​

jQuery

$( function() {

    ww=$(window).width();
    $('#container').css({'width':ww});
    cw=$('#container').width();
    cw3=cw/3;
    $('.item').css({'width':cw3});
    $('.item img').css({'width':cw3});

    $('#container').imagesLoaded(function(){
        $('#container').isotope({
            masonry:{
            columnWidth: cw3
        }
    });
});

  // $(window).smartresize(function(){
  //     $('#container').isotope({
  //         masonry:{
  //             columnWidth: cw3
  //         }
  //     });
  // });
    $(window).bind("resize", function() {
        $('#container').isotope({
            masonry:{
                columnWidth: cw3
            }
        });
    });
});​

回答1:

UPDATED:

Make sure the code for calculating the cw3 variable goes inside the window.resize() call.

$( function() {

    $(window).bind("resize", function() {

        ww=$(window).width();
        $('#container').css({'width':ww});
        cw=$('#container').width();
        cw3=parseInt(cw/3, 10);
        $('.item').css({'width':cw3});
        $('.item img').css({'width':cw3});

        $('#container').isotope({
            masonry: {
                columnWidth: cw3
            }
        });

    }).resize();

});​

Fun fact: always include radix parameter in parseInt() call

See http://jsfiddle.net/hongaar/9zJRh/3/