展开并折叠div

时间:2011-01-02 12:42:01

标签: javascript jquery jquery-animate if-statement

我有一个项目清单&他们拿着图像,每张图像是800w x 600 H.原来的div高度是800 W x 300 H.我想出了点击它时如何扩展div,但我想知道当你点击它时如何折叠它虽然已经扩大了。现在我只是进一步扩展div

  $('.expand').bind('click', function() {
  var currHeight = $(this).css('height').replace(/px/,'');
  currHeight = currHeight * 1;
  var newHeight = currHeight + 500;
  $(this).animate({
     height: newHeight
  },1000);

 });

关于如何创建if else statement的任何想法,如果div已经展开,然后在点击时折叠,或者如果div崩溃,则展开到#x px。

5 个答案:

答案 0 :(得分:2)

您可以检测当前的高度和分支:

$('.expand').bind('click', function() {
  var $this = $(this),
      height = $this.height();
  if (height > 500) {
    height -= 500;
  }
  else {
    height += 500;
  }
  $this.animate({
     height: height
  },1000);
});

我在那里做了其他几件事。您可以使用height而不是css('height')来获取没有单位的值,也不需要使用* 1技巧。我还完成了$(this) 一次并重复使用它,因为在调用$()函数时会涉及多个函数调用和分配。 (这里并不重要,但如果你没有比你想要的更长时间(通过一个闭包等),这是一个很好的习惯。)

或者,您可以记住,您已采用另一种方式(使用data功能):

$('.expand').bind('click', function() {
  var $this = $(this),
      height = $this.height(),
      expanded = $this.data('expanded');
  if (expanded) {
    height -= 500;
  }
  else {
    height += 500;
  }
  $this.data('expanded', !expanded);
  $this.animate({
     height: height
  },1000);
});

或者将它们组合起来以存储原始高度,以防它受到其他东西的影响:

$('.expand').bind('click', function() {
  var $this = $(this),
      height = $this.height(),
      prevHeight = $this.data('prevHeight');
  if (prevHeight) {
    height = prevHeight;
    $this.data('prevHeight', undefined);
  }
  else {
    $this.data('prevHeight', height);
    height += 500;
  }
  $this.animate({
     height: height
  },1000);
});

接受你的选择!

答案 1 :(得分:2)

我会使用CSS在原始版本和扩展版本中设置div的高度,然后在单击div时,切换类以更改高度:

/* CSS for the height */
.expand {
    height: 300px;
}
.expand.expanded {
    height: 600px;
}

然后在点击方法中,只需:

$(this).toggleClass("expanded");

答案 2 :(得分:0)

您可以在click活动时.height().animate() height +=-=相应地检查.toggle()({{ {1}}支持),像这样:

.animate()

或者,使用{{3}},如下所示:

$('.expand').click(function() {
  $(this).animate({ 
    height: $(this).height() > 300 ? "+=500px" : "-=500px" 
  }, 1000);
});

答案 3 :(得分:0)

jQ的一些指示:

.click(function(){})
.css({height: "300*1px"}) // Why are you multiplying Anything by ONE?!

你可以使用

if($(this).css("height") == "300px") {
Do stuff
} else { 
Do other stuff
}

编辑:但上面的其他选项要好得多。

答案 4 :(得分:0)

Pure Jquery,请查看文档Jquery Animate

$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    height: "toggle"
  }, {
    duration: 5000,
    specialEasing: {
      height: "linear"
    },
    complete: function() {
      //DO YOUR THING AFTER COMPLETE
    }
  });
});
相关问题