jQuery animate() 方法为创建自定义动画的方法。

语法

$(selector).animate({params}, speed, callback);

参数

  • params 参数定义了要设置动画的 CSS 属性。
  • speed 参数是可选的,用于指定效果的持续时间。可以设置为"slow"、"fast"或毫秒。
  • callback 参数也是可选的,它是动画完成后执行的函数。

例子

简单的例子

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>   
$(document).ready(function(){  
    $("button").click(function(){  
        $("div").animate({left: '450px'});  
    });  
});  
</script>   
</head>  
<body>  
<button>点击</button>  
<p>简单的 animation 例子:</p>  
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>  
</body>  
</html> 
注意:所有 HTML 元素的定位都是static。如果要操纵它们的位置,请将元素的 CSS 位置属性设置为相对、固定或绝对定位。

多个属性的例子

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>   
$(document).ready(function(){  
    $("button").click(function(){  
        $("div").animate({  
            left: '250px',  
            opacity: '0.5',  
            height: '150px',  
            width: '150px'  
        });  
    });  
});  
</script>   
</head>  
<body>  
<button>点击</button>  
<div style="background:#125f21;height:100px;width:100px;position:absolute;"></div>  
</body>  
</html> 

使用相对位置的例子

可以通过加减修改元素的位置。

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>   
$(document).ready(function(){  
    $("button").click(function(){  
        $("div").animate({  
            left: '250px',  
            height: '+=150px',  
            width: '+=150px'  
        });  
    });  
});  
</script>   
</head>  
<body>  
<button>点击</button>  
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>  
</body>  
</html> 

使用预定义值

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>  
<script>   
$(document).ready(function(){  
    $("button").click(function(){  
        $("div").animate({  
            height: 'toggle'  
        });  
    });  
});  
</script>   
</head>  
<body>  
<button>点击</button>  
<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>  
</body>  
</html>