jQuery 动画

前几节的效果都是现成的;而 animate() 方法允许你自定义动画:自己指定要变化的 CSS 属性和目标值,jQuery 会平滑地把元素从当前状态过渡过去,是做出炫酷动效的核心工具。

animate() 语法

$(selector).animate({ 样式属性: 目标值 }, 速度, 回调函数)
// 0.5 秒内把段落左内边距变为 50px
$('p').animate({ paddingLeft: '50px' }, 500);

注意:CSS 属性名要写成驼峰式,例如 padding-left 要写成 paddingLeftbackground-color 写成 backgroundColor

同时操作多个属性

对象里可以一次写多个属性,动画会同步进行:

$('#box').animate({
    left: '200px',          // 向右移动 200px
    opacity: '0.5',         // 透明度变为 0.5
    height: '150px'         // 高度变为 150px
}, 1000);

使用相对值与队列

  • 相对值:目标值以 +=-= 开头,表示在当前位置上增减。
  • 队列:对同一元素连续调用多个 animate(),动画会按顺序逐个执行(排队),而不是同时进行。
// 每次点击都在当前左边距基础上再加 100px
$('#btn').click(function () {
    $('#box').animate({ left: '+=100px' }, 500);
});

完整示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<!-- 引入 jQuery(https://example.com 为占位地址,实际使用时请替换为真实 CDN 或本地文件) -->
<script src="https://example.com/jquery.min.js"></script>
<style>
#box { position: relative; width: 80px; height: 80px;
       background: #7cc7ff; text-align: center; line-height: 80px; }
</style>
</head>
<body>
<button id="move">走两步</button>
<div id="box">小方块</div>

<script>
$(function () {
    $('#move').click(function () {
        // 效果:先向右移 150px,再向下移 100px(队列依次执行)
        $('#box').animate({ left: '+=150px' }, 600)
                 .animate({ top: '+=100px' }, 600);
    });
});
</script>
</body>
</html>

animate() 的限制

animate() 不能直接动画颜色(如 colorbackground-color),这类属性需要借助 jQuery Color 插件或改用 CSS 过渡实现。动画目标属性一般应是数值型(宽高、定位、透明度、内边距等),动画对象需配合 position 定位才能移动。

小结

animate() 用"属性 + 目标值"的方式自由定义动画:支持多属性同步、+= 相对值以及动画队列。下一节学习如何用 stop() 控制排队中的动画。

笔记加载中…