如何使用jquery从底部向上动画更改div高度

6
有没有办法使 div 盒子的高度从底部到顶部进行动画变化,而不是从顶部到底部?
这个 div 盒子是绝对定位的,类似于一个幕布,遮盖在它下面的内容上。
3个回答

5

为什么不使用slideUp() / slideDown()

因为如果多次/快速鼠标操作,容易出现错误。即使在演示中使用.stop()方法,也无法实现以下结果:


这里是一个稍微修改的方法,使用.animate()和高度切换: (只需要:position:absolute; bottom:0px; display:none;

演示1(一种好的方法)

$('.box').hover(function(){
  $(this).find('.curtain').stop().animate({height: 'toggle'});
});

演示 2

另一种方法是:

var boxHeight = $('.box').innerHeight();  // get element height

$('.curtain').css({top:boxHeight}); // push 'curtain' down

$('.box').hover(function(){
  $(this).find('.curtain').stop().animate({top: 0});  // animate to desired top distance
},function(){
  $(this).find('.curtain').stop().animate({top: boxHeight}); // and on mouseout - back down
});

兄弟,谢谢。我更喜欢Demo 2,因为我需要控制高度。 - MakkyNZ
1
@MakkyNZ 也向你致敬!我考虑了一下,所以给了一个例子!;) - Roko C. Buljan

0

您可以通过同时动画化顶部和高度来实现此效果。您只需要确定最终的高度即可。

例如,假设您有:

#mydiv{
    top: 200px;
    height: 300px;
    width: 100px;
    background-color: red;
    position: absolute;
};

如果您想要最终得到动画效果的 div:

#mydiv{
    top: 0px; /* new top */
    height: 500px; /* new height */
    width: 100px;
    background-color: red;
    position: absolute;
};

jQuery代码,当您单击div时:

$("#mydiv").on("click", function(){
   $('#mydiv').animate( {"top": "0px", "height": "500px" } );
});

0
$('div').slideUp();

这个使用.slideUp()来使div从底部到顶部以动画方式变为0px高度


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接