jQuery.lazyload+masonry改良圖片瀑布流代碼

字號:


    這里主要是使用jQuery.lazyload配合masonry實現(xiàn)瀑布流的重新排列,有時候網(wǎng)站的速度慢,圖片加載慢,獲取不到圖片的寬度和高度,所以使用lazyload可以在圖片加載完之后,進行瀑布流的重新排列。
    實現(xiàn)方法如下:(這里只發(fā)jquery了,相關html代碼請各位自己腦補一下吧,我就不發(fā)了,哈哈)
    /**
     * 自動刷新
     * @type {*|jQuery|HTMLElement}
     */
    var $container = $('#main');
    $container.imagesLoaded( function(){
      $container.masonry({
        itemSelector : '.item',
        columnWidth:205,
        gutterWidth:10,
        isAnimated: true
      });
    });
    var pre_href;
    //滾動
    $(window).scroll(function(){
      // 當滾動到最底部以上100像素時, 加載新內容
      if ($(document).height() - $(this).scrollTop() - $(this).height()<100) {
        ajax_load_data();
      }
    });
    function ajax_load_data(){
      var href = $('#page-nav').find('.nextprev').attr('href');
      if(href && href != pre_href){
        console.log('href = '+href);
        pre_href = href;
        $.ajax({
          url:href,//獲取元素列表的地址
          data:{'act':'ajax_wap_index'},
          dataType:'json',
          type:'post',
          beforeSend:function(){
            show_loading_body();
          },
          complete:function(){
            show_loading_body();
          },
          success:function(data){
            if(data.status != undefined && data.status == 'ok'){
              if(data.html){
                var $boxes = $( data.html );
                $container.append( $boxes ).masonry("appended", $boxes, true);//追加元素
                $container.imagesLoaded(function () {
                  $container.masonry();
                });//加載完圖片后,會實現(xiàn)自動重新排列。【這里是重點】
              }
              if(data.str_pages){
                $('#page-nav').html(data.str_pages);//設置下一個分頁的地址?!究梢宰约貉a充】
              }
            }
          }
        });
      }
    }