计算div宽度并插入clear div

时间:2012-02-21 09:45:22

标签: jquery

我有这段代码。

<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%或接近,则在标记中添加一个带有clear class的div。

但是,我不知道如何开始。 div都是百分比。

更新: 对于响应式内容,我稍微更改了代码,因此可以添加或删除它。我还有一个公司的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);

2 个答案:

答案 0 :(得分:2)

  1. 使用.containerwidth()函数
  2. 计算outerWidth()宽度
  3. $('.container div').each(function() { })计算每个div宽度
  4. 如果您需要宽度,请使用.after()函数插入清除元素
  5. 希望这会有所帮助。

答案 1 :(得分: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/

相关问题