1.css3的transition;
实例:鼠标移入时盒子宽度逐渐变大为300px
<style>
div
{
width:100px;
height:100px;
background:blue;
transition:width 2s;
-moz-transition:width 2s; /* Firefox 4 */
-webkit-transition:width 2s; /* Safari and Chrome */
-o-transition:width 2s; /* Opera */
}
div:hover
{
width:300px;
}
</style>
<div></div>
2.CSS3的animattion+keyframes;
实例:盒子左右无限循环运动
<style>
div
{
width:100px;
height:100px;
background:red;
position:relative;
animation:mymove 3s infinite alternate;
-webkit-animation:mymove 3s infinite alternate; /*Safari and Chrome*/
}
@keyframes mymove
{
from {left:0px;}
to {left:200px;}
}
@-webkit-keyframes mymove /*Safari and Chrome*/
{
from {left:0px;}
to {left:200px;}
}
</style>
<div></div>
3.使用window.setTimout()或者window.setInterval();
实例:盒子左右无限循环运动
<style>
#demo {
width: 100px;
height: 100px;
background: red;
position: relative;
}
</style>
<div id="demo" style="left:0;"></div>
<script>
var left = 0
, der = 0;
setInterval(function () {
left = document.querySelector("#demo").style.left;
if (left == "0px") {
der = 2;
}
if (left == "300px") {
der = -2;
}
document.querySelector("#demo").style.left = parseInt(left) + der + "px";
}, 60)
</script>
此方法的缺点是,可能会出现卡顿的现象,动画不顺畅
4.使用jquery动画相关的API;
实例:改变盒子宽度
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".btn1").click(function(){
$("#box").animate({width:"300px"});
});
$(".btn2").click(function(){
$("#box").animate({width:"100px"});
});
});
</script>
</head>
<body>
<div id="box" style="background:#98bf21;height:100px;width:100px;margin:6px;">
</div>
<button class="btn1">Animate</button>
<button class="btn2">Reset</button>
</body>
</html>
当然jquery中实现动画的API可不止这些,除了自定义动画之外,还有
显示与隐藏:hide(),show(),toggle();
滑动:slideDown(),slideUp(),slideToggle();
淡入淡出:fadeIn(),fadeOut(),fadeToggle(),fadeTo();
动画的操作:delay(),stop(),finish();
5.window.requestAnimationFrame()方法;
实例:盒子左右无限循环运动
<style>
#demo {
width: 100px;
height: 100px;
background: red;
position: relative;
}
</style>
<div id="demo" style="left:0;"></div>
<script>
//处理兼容问题
window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
var left = 0
, der = 0;
function step() {
left = document.querySelector("#demo").style.left;
if (left == "0px") {
der = 2;
}
if (left == "300px") {
der = -2;
}
document.querySelector("#demo").style.left = parseInt(left) + der + "px";
requestAnimationFrame(step);
}
requestAnimationFrame(step);//动画开启
</script>
需要注意的是,如果想得到连贯的逐帧动画,函数中必须重新调用 requestAnimationFrame(),另外此方法是比较新的一种方法,需要注意下其兼容性的处理

本文介绍了使用CSS3实现平滑过渡与动画效果的方法,包括transition和animation属性,并展示了通过jQuery进行元素尺寸变化及多种内置动画操作的示例。
1801

被折叠的 条评论
为什么被折叠?



