css3动画和jquery动画使用中要注意的问题

前一阵子写demo的时候遇到这样一个问题,就是给元素添加css3或者jquery动画时,在动画结束前不能准确取到元素的css属性。

1. css3动画讨论

先看代码:

html: 

<div id="hehe"></div>
<button class="change">change</button>
<button class="get">get</button>

css:

#hehe {
    width: 100px;
    height: 100px;
    padding: 10px;
    background: red;
    -webkit-transition: all 10s ease-out;
    -moz-transition: all 10s ease-out;
    -o-transition: all 10s ease-out;
    transition: all 10s ease-out;
}

js: 

$(document).ready(function() {
    $('.change').click(function() {
        $('#hehe').width(400);
    });
    $('.get').click(function() {
        console.log($('#hehe').width());
    });
});

代码很简单。我们给hehe这个div添加了红色的背景色,并且使用了css3里的动画平滑效果css3 trasition(css3 trasition的使用方法可以参考这篇文章:http://www.w3cplus.com/content/css3-transition,写的很详细)。也就是说当hehe发生诸如宽高,背景或者是字体等css属性变化时候,会有ease-out(减速)平滑过渡效果,效果持续10秒。比如说我们点击change按钮,hehe的宽度会消耗10s的时间,慢慢增加到400px,产生动画效果。

问题来了:在动画进行过程中,我单击get按钮,控制台输出的hehe宽度是多少?

一开始我以为是400,因为点击change的时候,审查元素看到"<div id="hehe" style=" 400px;"></div>"。答案是否定的,我们得到的是动画进行过程中点击时刻hehe的宽度。

我们修改下console的代码:  

console.log($('#hehe').css('width');

这下我们看到在整个动画过程中,我们点击get,得到的都是400px。这说明jquery里面的width()是实时获取元素宽度的,而css('width')只是单纯的获取元素的css值,因为也是带单位的。

2.jquery动画讨论

jquery动画就比较好理解了。我们去掉css3 transition的css代码,用jquery的animate来代替。

$(document).ready(function() {
    console.log($('#hehe').width());
    $('.change').click(function() {
        $('#hehe').animate({ "400px"}, 10000);
    });
    $('.get').click(function() {
        console.log($('#hehe').width());
    });
});

由于jquery的动画实际上是动态的给元素添加style样式,所以无论我们是用width()还是css('width')来获取hehe的宽度都是动态变化的。不过也有一点不同,使用width得到的宽度是没有单位px的,而且都是整数;但是使用css('width')获得的宽度是带单位的,并且小数点后面位数很长。

总结:

讨论了这么多,其实关键就是要告诉大家,在使用动画的时候,如果立刻去获取还在变化中的css属性,尤其是宽高,很容易出现问题,必须等到动画结束后在去取这些元素的属性。或者你可以指定需要动画效果的css属性。打个比方,你要获得动画中的宽高,而实际上你想要的动画效果只是背景颜色的变化,那么你在写css3 transition的时候就可以这么写

-webkit-transition: background .7s ease-out;
-moz-transition: background .7s ease-out;
-o-transition: background .7s ease-out;
transition: background .7s ease-out;

这样动画效果只会表现在背景色,而宽高是不会动态变化了。

同样的,对css3动画中的另外两个效果transform(http://www.w3cplus.com/content/css3-transform)和animation(http://www.w3cplus.com/content/css3-animation)也做了测试,发现跟transition是一样的,动画过程中元素属性都是动态变化的,甚至在运用animation的时候,用css('width')这样得到的宽度也是变化的了。感兴趣的同学可以去试试。

因此我们在运用css3动画的时候还需要多多注意动画带来的影响。

原文地址:https://www.cnblogs.com/zmhaki/p/3372024.html