2014-04-27 8 views
0

내 웹 사이트에서 두 div가 동일한 길이가되도록 온라인에서 찾은 일부 코드가 있습니다. 그러나이 코드는 페이지가 새로 고쳐진 후에 만 ​​작동하며이 문제를 일으키는 원인을 알지 못합니다. 어떤 도움을 주시면 감사하겠습니다!Javascript는 페이지 새로 고침 후에 만 ​​작동합니다.

// EQUAL HEIGHTS 
$.fn.equalHeights = function(px) { 
    $(this).each(function(){ 
     var currentTallest = 0; 
     $(this).children().each(function(i){ 
      if ($(this).height() > currentTallest) { currentTallest = $(this).height(); } 
     }); 
    if (!px && Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified 
     // for ie6, set height since min-height isn't supported 
     if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); } 
     $(this).children().css({'min-height': currentTallest}); 
    }); 
    return this; 
}; 

// just in case you need it... 
$.fn.equalWidths = function(px) { 
    $(this).each(function(){ 
     var currentWidest = 0; 
     $(this).children().each(function(i){ 
       if($(this).width() > currentWidest) { currentWidest = $(this).width(); } 
     }); 
     if(!px && Number.prototype.pxToEm) currentWidest = currentWidest.pxToEm(); //use ems unless px is specified 
     // for ie6, set width since min-width isn't supported 
     if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'width': currentWidest}); } 
     $(this).children().css({'min-width': currentWidest}); 
    }); 
    return this; 
}; 

// CALL EQUAL HEIGHTS 
$(function(){ $('#equalize').equalHeights(); }); 
+0

이 코드를 .ready 블록으로 사용하십시오. – underscore

+2

스크립트를로드하는 순서를 확인하십시오. 함수를 사용하기 전에 함수에 사용 된 스크립트가로드되어 있습니까? –

+0

@samitha'$ (function() {...})'은'$ (document) .ready (function() {...}) '와 같습니다. [here] (https://api.jquery.com/jquery/#jQuery3)를 참조하십시오. –

답변

2

이 문제는 플러그인이 제대로 작성되지 않았기 때문에 발생합니다. 나는 당신을 위해 그것을 수정했고 이제는 효과가있다.

Working DEMO

플러그인 스크립트 :

// EQUAL HEIGHTS 
    $.fn.equalHeights = function(px) { 
     var currentTallest = 0; 
     $(this).each(function(){ 
      $(this).siblings().each(function(i){ 
       if ($(this).height() > currentTallest) { 
       currentTallest = $(this).height(); 
       } 
      }); 
     }); 

     if (!px && Number.prototype.pxToEm) { 
     currentTallest = currentTallest.pxToEm(); 
     } 
     $(this).siblings().css({'height': currentTallest, 'min-height': currentTallest}); 
     return this; 
    }; 

이 플러그인으로 일할 수있는 equalWidths 플러그인을 수정할 수 있습니다.

+1

감사합니다 - 나는 또한 주문과 그 작업을 지금 바꿨다 : D – Janey

0

모든 코드를 jquery 준비 함수에 넣으십시오. DOM 준비가되면 내부 준비 함수 코드가 실행됩니다.

$(document).ready(function(){ 
//your code 
}); 
+0

주석에서 언급했듯이'$ (function() {...})'은'$ (document) .ready (function() {...}) '과 동일하며 코드를 이미 넣었습니다 '$ (function() {...}); '에서. [API] (https://api.jquery.com/jquery/#jQuery3)에서 언급되었습니다. –

+0

게시하기 전에 시도했지만 작동하지 않았습니다! 그래도 고마워. – Janey

관련 문제