jquery函数仅在第一次单击时才能正常工作

时间:2016-10-25 10:31:56

标签: javascript 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>

1 个答案:

答案 0 :(得分: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');
  }
}