教程 jquery tutorial

自定义动画

除了基本的淡入淡出和滑动效果,jQuery 还提供 animate() 方法,用于自定义元素属性变化的动画过程。

animate 方法语法

js
$(selector).animate(properties, duration, easing, callback);
  • properties:要改变的 CSS 属性对象
  • duration:动画持续时间(如 "slow"、"fast" 或毫秒数)
  • easing:缓动函数(如 "swing" 或 "linear")
  • callback:动画完成后执行的函数

支持动画的属性示例

  • width、height
  • opacity
  • margin、padding
  • left、top(需设置定位)

示例代码

在线代码演示
源码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
  $(function () {
    $("#btnAnimate").click(function () {
      $("#box").animate(
        {
          width: "300px",
          height: "150px",
          opacity: 0.6,
          marginLeft: "50px",
        },
        800,
        "swing",
        function () {
          alert("动画完成!");
        }
      );
    });
  });
</script>

<button id="btnAnimate">执行自定义动画</button>

<div id="box" style="width: 150px; height: 100px; background: #9c27b0; margin-top: 10px" ></div>