欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jQuery中实现不定高度height属性过渡为auto的animate动画 有大用

var el = $('#first'),
    curHeight = el.height(),
    autoHeight = el.css('height', 'auto').height();
el.height(curHeight).animate({height: autoHeight}, 1000);


jQuery中想要用animate方法将元素的height属性从其它值过渡到auto值,首先想到的就是

JavaScript代码

复制
  1. $(this).animate({height:'auto'}, 300);


但是并不起作用。

这时需要换一种方法,思路是:

1、首先定义变量将当前的高度值保存下来。

JavaScript代码

复制
  1. var curHeight = $(this).height();


2、将元素高度临时改变为auto。

JavaScript代码

复制
  1. $(this).css('height', 'auto');


3、获取height为auto时的高度值。

JavaScript代码

复制
  1. var autoHeight = $(this).height();


4、执行动画,将curHeight 过渡到 autoHeight。

JavaScript代码

复制
  1. $(this).height(curHeight).animate({height: autoHeight}, 300);


连起来就是:

JavaScript代码

复制
  1. var el = $(this),

  2.    curHeight = el.height(),

  3.    autoHeight = el.css('height', 'auto').height();

  4. el.height(curHeight).animate({height: autoHeight}, 300);

这样就实现了高度从其它值过渡到auto的效果。

来自  https://www.qwqoffice.com/article.php?mod=view&tid=15




JQuery中animate的一些坑

auto

animate对auto支持的很不好,在做动画的时候很不方便。height,left等属性都不支持auto。 
对于height在每次执行animate之前通过.height()方法读取一下就好。 
对于left使用.position().left方法来读取。不过对于left来说还有一个问题,在改left或right之中的一个的时候需要把另一个置为auto,否则这两个会互相影响。position()方法并没有提供right的值,这时就要自己算出来咯~

var $menu = $("#menu"),
    $menuWidthControl = $(".sys-menu-widthControl");
//在顶部菜单栏不够宽时,向左或向右滑动
$(".sys-menu-left").mouseenter(function(){
    var menuFatherWidth = $menuWidthControl.width();
    var menuLeft = $menu.position().left;
    var menuWidth = $menu.width();
    $menu.css("right",menuFatherWidth-menuLeft-menuWidth);
    $menu.css("left","auto");
    $menu.animate({"right":"0px"},1000);
});
$(".sys-menu-right").mouseenter(function(){
    var menuLeft = $menu.position().left;
    $menu.css("left",menuLeft);
    $menu.css("right","auto");
    $menu.animate({"left":"0px"},1000);
});
$(".sys-menu-right,.sys-menu-left").mouseleave(function(){
    $menu.stop();
});
  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

  • 11

  • 12

  • 13

  • 14

  • 15

  • 16

  • 17

  • 18

  • 19

  • 20

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/exialym/article/details/51083794

来自  https://blog.csdn.net/exialym/article/details/51083794

普通分类: