开发者

jQuery - Animate height not working as expected

Can't seem to get this to work, any ideas?

http://jsfiddle.net/U92bM/

开发者_如何学C

JavaScript:

$('.articleSlide').each(function () {
    var current = $(this);
    current.attr("box_h", current.height());
});

$(".articleSlide").css("height", "100px");

$(".showHide").html('<a href="#">More</a>');

$('.showHide a').click(function() {
    var open_height = $(".articleSlide").attr("box_h") + "px";
    $(this).closest("articleSlide").animate({"height": open_height}, {duration: "slow" });  
});

HTML:

<div class="articleSlide">
    <!-- lots of text -->
</div>

<div class="showHide"></div>


try this instead:

$('.articleSlide').each(function() {
    var current = $(this);
    current.attr("box_h", current.height());
});

$(".articleSlide").css("height", "100px");

$(".showHide").html('<a href="#">More</a>');

$('.showHide a').click(function() {
    var open_height = $(".articleSlide").attr("box_h") + "px";
    $(this).parent().parent().children('.articleSlide')
        .animate({"height": open_height}, "slow" );
});

http://jsfiddle.net/maniator/U92bM/5/

You have to goto the anchor tag's grandparent in order to find the element you want to manipulate

works like a charm ^_^


You got the relationship between the elements wrong. closest searches for the closest ancestor but the articleSlide div is not an ancestor of the link. It is a sibling of its parent. This would work:

$(this).parent().prev().animate(...);

http://jsfiddle.net/U92bM/7/


Try binding your click event with .live() method since you're adding the anchor to the DOM dynamicly. Also, you dont need to add an attribute "box_h" to each '.articleSlide' giving them values of the 'current.height()'. Just use the height on time. Pretty much like this:

$('.showHide a').live('click', function() {
    var open_height = $(".articleSlide").height() + "px";
    $(this).closest("articleSlide").animate({"height": open_height}, {duration: "slow" });  
});

And what about:

$('.showHide a').click(function(e) {
    var open_height = $(e.target).height() + "px";
    $(this).closest("articleSlide").animate({"height": open_height}, {duration: "slow" });  
});

Use the "e.target" to make sure you get the right link's height. I assume you tested to make sure the .click() worked fine. You could also test the same animation but removing the "px" string since I tried this once and it worked. And you can remove entirely the ".each()" function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜