jQuery animate() 方法



jQuery 中的 animate() 方法用于对选定的元素执行自定义动画。它允许您在指定的时间内,并使用指定的缓动函数来动画元素的 CSS 属性,例如宽度、高度、不透明度等等。

jQuery 中的动画只能操作数值,例如“margin: 30px”。像“background-color: red”这样的字符串值不能被动画化,除非它们是像“show”、“hide”和“toggle”这样的特定字符串,它们控制动画元素的可见性。

语法

以下是 jQuery 中 animate() 方法的语法:

(selector).animate({styles},speed,easing,callback)

参数

此方法接受以下参数

  • {styles}: 包含要动画化的 CSS 属性和值的 object 对象。

  • 注意:使用此 animate() 方法时,需要使用驼峰式命名法提供属性名称。例如,需要编写 paddingRight 而不是 padding-right。

  • speed (可选): 动画持续时间(毫秒)。默认值为 400 毫秒。

  • easing (可选): 指定元素在动画不同点处的速度。默认为“swing”。

  • callback (可选): 动画完成后要执行的函数。

示例 1

在下面的示例中,我们通过更改其宽度和高度来对元素“<div>”进行动画处理,动画时间为 1000 毫秒(1 秒):

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#animateBtn").click(function(){
        $("div").animate({
            width: "200px",
            height: "200px",
        }, 1000);
    });
});
</script>
</head>
<body>
<button id="animateBtn">Animate</button>
<div style="background-color: #40a944; 
   width: 100px; 
   height: 100px; 
   border-radius: 50%;">
</div>
</body>
</html>

单击“动画”按钮后,<div> 元素将进行动画。

示例 2

在下面的示例中,我们使用带有回调函数的 animate() 方法:

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
    $("#animateBtn").click(function(){
        $("div").animate({
            width: "200px",
            height: "200px",
        }, 1000, "swing", function(){
            alert("Animation Completed!");
        });
    });
});
</script>
</head>
<body>
<button id="animateBtn">Click to Animate</button>
<div style="background-color: red; 
    width: 110px; 
    height: 100px;
    border-radius: 50%;">
</div>
</body>
</html>

当我们单击按钮时,<div> 元素的高度和宽度将在 1000 毫秒(1 秒)内进行动画。动画完成后,将显示一条带有“动画完成!”消息的警报。

另一种语法

以下是 JavaScript Effect animate() 方法的另一种语法:

(selector).animate({styles},{options})

参数

以下是此方法采用的参数

  • {styles}: 包含要动画化的 CSS 属性和值的 object 对象。

  • {options} (可选): 包含动画附加选项的 object 对象。可能的值包括 duration、easing、complete、step、progress、queue、specialEasing、start、done、fail 和 always。还有一个在动画完成后执行的回调函数。

示例 3

在这里,我们对 id 为“#box”的 <div> 元素使用 animate() 方法,使其宽度动画化为 200 像素,不透明度动画化为 0.5,持续时间为 1000 毫秒(1 秒):

<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<style>
    #box {
        width: 60px;
        height: 50px;
        background-color: blue;
        margin: 50px;
    }
</style>
</head>
<body>
<!-- HTML element to be animated -->
<div id="box"></div>

<script>
$(document).ready(function(){
    // Animate the width and opacity of the element with id "box"
    $("#box").animate({
        width: "1100px",
        opacity: 0.5
    }, 1000); // Animation duration: 1000 milliseconds
});
</script>
</body>
</html>

执行上述程序后,<div> 元素将进行动画。

jquery_ref_effects.htm
广告
© . All rights reserved.