动画效果(三)

   动画相关方法

   很多时候需要停止正在运行中的动画,jQuery为此提供了一个.stop()方法。它有两个可选参数:.stop(clearQueue, gotoEnd);clearQueue传递一个布尔值,代表是否清空未执行完的动画列队,gotoEnd代表是否直接将正在执行的动画跳转到末状态。

   html代码:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>动画效果</title>
    <script type="text/javascript" src="jquery-1.12.3.js"></script>
    <script type="text/javascript" src="demo.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
    <input type="button" class="button" value="按钮" />
    <input type="button" class="stop" value="停止" />
    <input type="button" class="ani" value="查找运动的动画" />
    <div id="box">
        box
    </div>
    <div id="pox">
        pox
    </div>
</body>
</html>

   style.css:

#box {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
}
#pox {
    width: 100px;
    height: 100px;
    background: green;
    position: absolute;
    top:150px;
}

   jQuery代码:

$(".button").click(function() {
    $("#box").animate({
        left:"800px"
    }, 3000);
});
$(".stop").click(function() {
    $("#box").stop(); //强制停止运行中的块
});

   jQuery代码如下:

$(".button").click(function() {
    $("#box").animate({left:"300px"}, 1000)
             .animate({bottom:"300px"}, 1000)
             .animate({width:"300px"}, 1000)
             .animate({height:"300px"}, 1000);
});

   ①如果有列队动画,停止的话,那么会停止掉第一个列队动画,然后继续执行后面的动画。

$(".stop").click(function() {
    $("#box").stop();
});

   ②第一个参数为true,就是停止并且清除后面的列队动画,动画即全面停止,默认值为false。

$(".stop").click(function() {
    $("#box").stop(true);
});

   ③第二个参数为true,停止后会跳转到末尾的位置上,默认值为false。

$(".stop").click(function() {
    $("#box").stop(true,true);
});

   总结:第一个参数表示是否取消列队动画,默认为false,如果参数为true,当有列队动画的时候,会取消后面的列队动画;第二参数表示是否到达当前动画结尾,默认为false,
如果参数为true,则停止后立即到达末尾处。

   有时在执行动画或列队动画时,需要在运动之前有延迟执行,jQuery为此提供了.delay()方法,这个方法可以在动画之前设置延迟,也可以在列队动画中间加上。

$(".button").click(function() {
    $("#box").delay(1000)
             .animate({left:"300px"})
             .animate({bottom:"300px"}).delay(2000)
             .animate({width:"300px"})
             .animate({height:"300px"});
});

   在选择器的基础章节中,我们提到过一个过滤器:animated,这个过滤器可以判断出当前运动的动画是哪个元素,通过这个特点,我们可以避免由于用户快速在某个元素执行动画时,由于动画积累而导致的动画和用户的行为不一致。

//递归执行自我,无线循环播放
$("#box").slideToggle("slow", function() {
    $(this).slideToggle("slow", arguments.callee);
});
//停止正在运动的动画,并且设置绿色背景
$(".ani").click(function() {
    $(":animated").stop().css("background", "blue");
});

   动画全局属性

   jQuery提供了两种全局设置的属性,分别为:$.fx.interval,设置每秒运行的帧数;$.fx.off,关闭页面上所有的动画。

   $.fx.interval属性可以调整动画每秒的运行帧数,默认为13毫秒,数字越小越流畅,但可能影响浏览器性能。

$.fx.interval = 200; //默认为13
$(".button").click(function() {
    $("#box").toggle(1000);
});

   $.fx.off属性可以关闭所有动画效果,在非常低端的浏览器,动画可能会出现各种异常问题导致错误。而jQuery设置这个属性,就是用于关闭动画效果的。

$.fx.off = true; //关闭动画,默认为false

 

posted @ 2016-04-25 16:35  叶十一少  阅读(197)  评论(0编辑  收藏  举报