2016-10-25 2 views
0

Я есть эта функцияJQuery функция корректно работает только на первый щелчок

$(".plusmenus1").on('click', function() { 
    $('.plusmenus1 i').toggleClass("fa-plus fa-minus"); 
    $("#care_and_washing").toggleClass("collapsed_MB "); 
    changeHeight(); 
}); 
$(".plusmenus2").on('click', function() { 
    $('.plusmenus2 i').toggleClass("fa-plus fa-minus"); 
}); 

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

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

    if (!$("#care_and_washing").hasClass("collapsed_MB")) { 
     $('#careheight').css('height', divHeight + 'px'); 
    } else { 
     $('#careheight').css('height', '10px'); 
    } 
} 

он работает, но он получает var divHeight = $("#care_and_washing").height() + $("#demo").height(); правильно только на первый щелчок после того, что он получает var без +, так что добавляет только height из #care_and_washing

HTML (я постараюсь добавить только то, что нужно)

<div class="plusmenus1"><i data-toggle="collapse" data-target="#demo" style="float: left; position: relative; top: 3px; padding-right: 5px; color: black; font-size: 10px;" class="fa fa-plus collapsed" aria-hidden="true"></i> 
<p id="care_and_washing" data-toggle="collapse" data-target="#demo" class="collapsed collapsed_MB" style="font-family: 'NiveauGroteskMedium'; font-size: 11px; color: black;">Care & Washing</p> 
</div> 
<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> 
+0

Это будет легче помочь, если вы покажете свой HTML тоже. –

+0

@ Додоридо ok Позвольте мне добавить его – Marwane

+0

@ Marwane, кажется, работает нормально https://jsfiddle.net/8odoros/mt7rtvvb/ –

ответ

2

Hidden_Element.height() и Hidden_Element.width() будет 0 так что вам нужно, чтобы показать, чтобы получить высоту и скрыть снова, как этот

function changeHeight() { 
    var care_h = $("#care_and_washing").height(); 
    var demo_h = $("#demo").height(); 

    demo_h = demo_h == 0 ? $("#demo").show().height() : demo_h; 

    $("#demo").hide(); 

    var divHeight = care_h + demo_h; 

    if (!$("#care_and_washing").hasClass("collapsed_MB")) { 
    $('#careheight').css('height', divHeight + 'px'); 
    } else { 
    $('#careheight').css('height', '10px'); 
    } 
}