jQuery-动画方法Animate
时间:2020-02-23 14:46:05 来源:igfitidea点击:
在本教程中,我们将学习jQuery中的动画。
animate()
我们使用" animate()"方法对元素的属性进行动画处理。
语法
$(selector).animate({ property: value; });
在下面的示例中,我们有一个id为" sample-div1"的div,我们将使用" animate()"方法将其高度增加到100px。
HTML
<div id="sample-div1"> <p>Hello World</p> </div>
CSS
#sample-div1 { border: 1px solid #111; }
jQuery
$("#sample-div1").animate({ "height": 100 });
动画时长
我们还可以通过将时间(以毫秒为单位)传递给" animate()"方法来设置动画的持续时间。
语法
$(selector).animate({ property: value; }, duration);
在下面的示例中,我们有一个id为" sample-div1"的div,并将使用" animate()"方法在3000毫秒内将其高度增加到20%。
HTML
<div id="sample-div1"> <p>Hello World</p> </div>
CSS
#sample-div1 { border: 1px solid #111; }
jQuery
$("#sample-div1").animate({ "height": "20%" }, 3000);
动画完成
我们还可以添加将在动画完成后执行的函数。
语法
$(selector).animate({ property: value; }, duration, complete);
在下面的示例中,我们有一个id为" sample-div1"的div,并使用" animate()"方法在3000毫秒内将其高度增加到200px。
动画完成后,我们将使用css()
方法返回div的高度。
HTML
<div id="sample-div1"> <p>Hello World</p> </div>
CSS
#sample-div1 { border: 1px solid #111; }
jQuery
$("#sample-div1").animate({ "height": 200 }, 3000, function() { console.log("Height: " + $(this).css("height")); //this will print "Height: 200" });
$(this)指的是我们要动画的元素。
动画缓动
缓动函数指定动画在动画中不同点处进行的速度。
默认情况下,值为" swing"。
jQuery提供了两个缓动值,两个值是'swing'和'linear'。
线性价值放松以持续的步伐进行。
语法
$(selector).animate({ property: value; }, duration, easing, complete);
在以下示例中,我们将在1000毫秒内将id为" sample-div1"的div的高度更改为200px。
我们正在使用"线性"缓动,当动画完成时,我们正在打印"完成!"。
在浏览器控制台中。
$("#sample-div1").animate({ "height": "200px" }, 1000, "linear", function(){ console.log("Done!"); });