2012-02-21 66 views
1

我有這段代碼。計算div寬度並插入清除div

<div class="container"> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
    <div></div> 
</div> 

容器DIV的孩子有不同的高度,這意味着我得到浮動問題。我想要一些查看兒童寬度的jquery,計算它們,如果它們是100%或接近,則將帶有清除類的div添加到標記中。

但是,我不知道如何開始。 divs都是百分比。

更新: 對於響應式的東西,我改變了一下代碼,所以它可以被添加或刪除。此外,我曾在公司的JavaScript的球員之一優化它

$(window).load(function() { 
    clearContext(); 
}); 

$(window).resize(function() { 
    clearContext(); 
}); 



function clearContext(){ 
    $('.contextElements .spot').addLineBreak(); //Choose target 
} 



// PLUGIN 
(function($) { 
    $.fn.addLineBreak = function() { 
     var $this = this, 
      minLeft = 0; 

     //clear 
     $('.removeDiv').remove(); 

     minLeft = $this.first().position().left; 

     $this.each(function() { 
      var $elm = $(this), 
       position = $elm.position(); 

      if (position.left > minLeft && $elm.prev().position().left >= position.left) {   
       $elm.before('<div class="clear removeDiv"></div>'); 
      } 
     }); 

     return this; 
    } 
})(jQuery); 
+0

定義什麼 '接近'意味着在你的情況下。你想在哪裏添加清算股票? – 2012-02-21 09:49:42

+0

使用jQuery/javascript解決佈局問題是沿着漫長的黑暗路徑邁出的第一步... – 2012-02-21 09:50:33

回答

1

出於類似的目的,我寫了這個插件前一陣子:

(function($) { 
    $.fn.extend({ 
    addLineBreak: function(css) { 
     var minLeft = $(this).position().left; 

     return $(this).each(function() { 
     var position = $(this).position(); 
     if (position.left > minLeft && $(this).prev().position().left >= position.left) { 
      $(this).css(css); 
     } 
     }); 
    } 
    }); 
})(jQuery); 

用法:

$('.container div').addLineBreak({clear: 'left'}); 

演示:

http://jsfiddle.net/HLXvy/

+0

看起來完全像我需要的東西。當我執行它時,我的控制檯中出現錯誤。任何想法可能是 「Uncaught TypeError:無法讀取null的屬性'左' – Johansrk 2012-02-21 10:11:51

+0

@Johansrk可能是您的選擇器匹配零個元素。然後它會將這個錯誤放在'var minLeft = $(this).position()。left;'這一行中。 – Yoshi 2012-02-21 10:13:26

+0

確定它現在的作品..真棒插件你已經..謝謝 – Johansrk 2012-02-21 10:56:22

2
  1. 計算.container寬度與width()outerWidth()功能
  2. $('.container div').each(function() { })計算每個div的寬度
  3. 如果寬度是你所需要的,與.after()功能插入清除元素

希望這會有所幫助。