2012-02-21 2 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의 자식에게는 높이가 다르기 때문에 플로트 문제가 발생합니다. children 너비를보고 jquery를 사용하여 계산하고 싶습니다. 100 % 또는 가까운 경우 명확한 클래스가있는 div가 마크 업에 추가됩니다.

그러나 시작하는 방법에 대한 단서가 없습니다. div는 모두 비율로 표시됩니다.

업데이트 : 반응이있는 항목에 대해서는 코드를 약간 변경했기 때문에 추가하거나 제거 할 수 있습니다. 또한 나는 회사의 자바 스크립트 사람 중 하나가

$(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

무엇을 '에 가까운'를 정의 나는이 얼마 전에 플러그인을 작성했습니다 유사한 목적 –

+0

레이아웃 문제를 해결하기 위해 jQuery/javascript를 사용하면 길고 어두운 경로를 따라 가야합니다. –

답변

1

당신의 상황에서 의미합니다. 클리어링 사업부는 어디에서 추가할까요?
+0

정확히 내가 원하는 것과 같습니다. 콘솔을 구현할 때 콘솔에 오류가 발생합니다. 무엇이 될 수있는 아이디어 "잡히지 않은 TypeError : null의 속성 '왼쪽'을 읽을 수 없습니다." – Johansrk

+0

@Johansrk 선택기가 0 요소와 일치 할 수 있습니다. 그런 다음이 오류를'var minLeft = $ (this) .position(). left;'에 던져 버릴 것이다. – Yoshi

+0

이제 괜찮습니다. 당신이 만든 멋진 플러그인 .. 고마워요. – Johansrk

2
    width() 또는 outerWidth() 기능
  1. 계산 .container
  2. $('.container div').each(function() { }) 계산 각각 폭이 당신이, 필요한 경우 폭
  3. div에 최적화했다 .after() 기능 삽입 투명 요소

희망이 도움이 될 것입니다.

(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/

관련 문제