2012-09-28 85 views
1

我有一個列表,其中li圖像左移,並根據窗口大小(使用媒體查詢和不同的img大小)將它們排列在不同數量的行中。元素之間的垂直間距通過使用底部邊距來完成。但是,列在最下面一行的列表項不需要底部邊距:它在頁腳上方留下了太多空間。我想通了,使用JQuery擺脫對底部行上的項目下邊距(可能是低效的)方式:有時window.resize需要兩個調整大小來實際執行我的javascript

bottomMargin(); 
    window.onresize = bottomMargin; 

    function numberOfRows() { 
     var noOfRows = 0; 
     $('#gallery ul li').each(function() { 
      if($(this).prev().length > 0) { 
       if($(this).position().top != $(this).prev().position().top) 
        noOfRows++; 
      } 
      else 
       noOfRows++; 
     }); 
     return noOfRows; 
    } 

    function whichRow() { 
     var thisRow = 0; 
     $('#gallery ul li').each(function() { 
      if($(this).prev().length > 0) { 
       if($(this).position().top == $(this).prev().position().top) { 
        $(this).data('row', thisRow); 
       } 
       else { 
        thisRow++; 
        $(this).data('row', thisRow); 
       }  
      } 
      else { 
       thisRow++; 
       $(this).data('row', thisRow); 
      } 
     }); 
    } 

    function bottomMargin() {      
     whichRow(); 
     var totalRows = numberOfRows(); 
     $('#gallery ul li').each(function() { 
      if ($(this).data('row') == totalRows) 
       $(this).css('margin-bottom', '0%'); 
      else 
       $(this).css('margin-bottom', ''); 
     }); 
    } 

這將工作大部分時間。但是,如果我從加載頁面的位置調整了多個媒體查詢的大小,它將不會改變初始窗口大小的邊距。在擺脫那個令人討厭的底部邊緣之前,我必須稍微調整大小。爲什麼需要兩次調整?

回答

0

嗯,聽起來像是你在做瀏覽器繪製頁面之前做數學和應用邊距的衝突,或者其他與時間有關的事情。嘗試調節您的調整大小回調:

var resizeTimer = 0; 

$(window).on('resize', function() { 
    clearTimeout(resizeTimer); 
    resizeTimer = setTimeout(bottomMargin, 30); 
}) 

function bottomMargin() { 
    ... 
} 
+0

謝謝!完全解決它,只需要調整實際的setTimeout毫秒設置。 – marker004

相關問題