2016-10-25 3 views
3

クラスcollapsedがその要素にない場合は、別の要素の高さを取得するためにdivが必要です(私はブートストラップの切り替えを使用しています)。jQueryで要素の高さを動的に変更

ページが読み込まれても、要素とクラスをクリックすると機能します。collapsedが削除されます。の高さは変更されません。

$(document).ready(function() { 
 
    var divHeight = $("#care_and_washing").height(); 
 
    if (!$("#care_and_washing").hasClass("collapsed")) { 
 
    $('#careheight').height(divHeight); 
 
    } else { 
 
    $('#careheight').height("10px"); 
 
    } 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p id="care_and_washing" data-toggle="collapse" data-target="#demo" class="collapsed" style="font-family: 'NiveauGroteskMedium'; font-size: 11px; color: black;">Care & Washing</p> 
 

 
<div style="cursor: default; padding-left: 13px;" id="demo" class="collapse"> 
 
    <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Dry Flat</p> 
 
    <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Do Not Bleach</p> 
 
    <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Tumble Dry Low</p> 
 
    <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Iron Low</p> 
 
    <p style="font-family: Questrial, sans-serif; font-size: 10px;">• Hand Wash</p> 
 
</div> 
 

 
<div id="careheight"></div>

答えて

3

機能のみ文書負荷に呼び出されたためです。

$(document).ready(function(){ 
    changeHeight(); 
}) 

$('.element-you-want-to-click').click(function() { 
    changeHeight() 
}); 

function changeHeight() { 
    var divHeight = $("#care_and_washing").height(); 

    if (!$("#care_and_washing").hasClass("collapsed")) { 
     $('#careheight').height(divHeight); 
    } 

    else { 
     $('#careheight').height("10px"); 
    } 
} 

これは、最初の機能が動作していればうまくいくはずです。

+0

私はあなたに感謝します – Marwane

+0

それはjsfiddleで動作しますが、私のサイトでは動作しません... – Marwane

+0

それは奇妙です。私はそれをチェックアウトできるように私にリンクを送ることができますか? – Roberrrt

関連する問題