jquery - 如何通过单击其他位置自动返回默认高度切换

时间:2015-02-28 22:35:06

标签: javascript jquery

在这里,我有一个工作toogle代码,所以我添加了一些代码,当点击另一个地方也返回默认高度(32px),但不工作。

var toggled = false;
$('.dropdown-toggle').click(function() {
  $('.changeHeight').css('height', toggled ? '32px' : '65px');
  toggled = !toggled;
});

$(document).click( function(){  // if click another place will set default height
    $('.changeHeight').css('height','32');
});

2 个答案:

答案 0 :(得分:2)

元素.dropdown-toggledocument的一部分。单击它将触发两个事件处理程序。单击它后,您必须阻止通过stopPropagation()通知文档事件处理程序。像这样:

$('.dropdown-toggle').click(function(e) {
    e.stopPropagation();
    $('.changeHeight').css('height', toggled ? '32px' : '65px');
    toggled = !toggled;
});

答案 1 :(得分:0)

你错过了“px”吗?

$(document).click( function(){  // if click another place will set default height
    $('.changeHeight').css('height','32px');
});

您还可以在切换上添加一个类,然后再将其删除。在jQuery中查看有关toggleClass的更多信息

$('.dropdown-toggle').click(function() {
  $('.changeHeight').toggleClass("toggled");
});