如何在slideToggle函数中更多/更少地更改div高度

我怎样才能更新我的代码,所以我可以用slideToggle()更改

高度,现在它几乎是正确的, 但是当我点击一个"read_more"并点击另一个时它就不对了。 我需要什么时候slideDown显示隐藏的p并将主

更改为特定高度,何时是slideUp隐藏此p并更改

之前的特定高度( "... Read More" base .main height, "... Read Less"新的。 .main高度”。

请参阅下面的演示或代码。

HTML

 

Lorem ipsum dolor sit amet

Ut enim ad minim veniam, quis nostrud exercitation.

Duis aute irure dolor in reprehenderit in voluptate.

... Read More

Consectetur adipisicing elit

On the other hand, we denounce with righteous.

Gemoralized by the charms of pleasure of the moment.

... Read More

Sed do eiusmod tempor incididunt

The wise man therefore always holds.

Et harum quidem rerum facilis est et expedita distinctio.

... Read More

CSS

 .main { border:1px solid blue; height: 260px; padding: 5px; } h1,h2,h3 { font-size: 18px; color: #96bc33; } p { margin: 0; font-size: 13px; } .more { display:none; } .read_more { cursor: pointer; color: red; } 

JavaScript的

 var rm = $(".read_more"), moreText = "... Read More", lessText = "... Read Less", i = 0 ; rm.click(function () { var $this = $(this); rm.not($this).text(moreText).prev(".more").slideUp(); $this.text($this.text() == moreText ? lessText : moreText).prev(".more").slideToggle("normal"); $(".main").animate({height:(++i % 2) ? 280 : 260}, "normal"); }); 

我升级了你的jsFiddle:

http://jsfiddle.net/GwkQN/

所做的更改是:

  • 容器中删除了height属性

  • rm.click重构了你的脚本

我不确定你的代码是否除了slideToggle之外还有别的东西,但是这个单行代码可能会完成你需要的所有东西。

 $(this).prev('.more').slideToggle(); 

更改了jQuery代码:

 var rm = $(".read_more"), moreText = "... Read More", lessText = "... Read Less"; rm.click(function () { $(this).prev('.more').slideToggle(); if($(this).text()==moreText){ $(this).text(lessText); }else{ $(this).text(moreText); } }); 

改变了CSS:

 .main { border:1px solid blue; padding: 5px; } 

如果你需要特定的高度你可以使用css属性: min-height: 260px;

 .main { border:1px solid blue; padding: 5px; min-height: 260px; } 

JS

 var rm = $(".read_more"), moreText = "... Read More", lessText = "... Read Less"; rm.click(function () { var $this = $(this); rm.not($this).text(moreText).prev(".more").slideUp(); $this.text($this.text() == moreText ? lessText : moreText).prev(".more").slideToggle("normal"); }); 

小提琴

试试这个,

 jsfiddle.net/4MfLw/8/ 

我已经更新了你的代码

我已经从你的“主”类的css中删除了“height”属性。我也评论了你的动画代码,我编写了代码,如果它们是开放的,则将所有其他“更多”的div滑开