鏈式運動
一芝雪、Html布局
<body>
<div id="test"></div>
</body>
二蕴忆、Css樣式
<style>
body{
margin:0;
padding: 0;
}
#test{
width:200px;
height: 100px;
background: yellow;
margin-bottom: 20px;
filter:alpha(opacity:30); /*針對 IE8 以及更早的版本*/
opacity:0.3;
border: 4px solid blue;
/*添加一個寬度為4px的邊框*/
}
</style>
三哈误、Js部分
startMove = function(obj,attr,iTarget,fn){
//鏈式運動需要添加一個回調(diào)函數(shù)作為參數(shù)
clearInterval(obj.timer);
//開啟定時器前先關(guān)閉所有定時器
obj.timer = setInterval(function(){
var icur = 0;
if(attr == 'opacity'){
icur = Math.round(parseFloat(getStyle(obj,attr))*100);
//如果是opacity則應(yīng)用parseFloat 之后×100是為了方便兼容alpha
//parseFloat取到的是多位小數(shù) 所以用Math.round四舍五入
}else{
icur = parseInt(getStyle(obj,attr));
}
var speed = (iTarget -icur)/8;
speed = speed > 0?Math.ceil(speed):Math.floor(speed);
//緩沖運動 speed>0向上取整 speed<0向下取整
if(icur == iTarget){
clearInterval(obj.timer);
if(fn){
fn(); //上一個動作完成時判斷是否需要執(zhí)行下一個動作
}
}else{
if(attr == 'opacity'){
obj.style.filter = 'alpha(opacity: '+(icur+speed)+')';
//針對 IE8 以及更早的版本
obj.style.opacity = (icur+speed)/100;
//針對FF Chrome
}else{
obj.style[attr] = icur + speed + "px";
}
}
},30)
}
window.onload = function(){
var myDiv = document.getElementById("test");
myDiv.onmouseover = function(){
//鏈式調(diào)用
startMove(this,'width',400,function(){
startMove(myDiv,'height',400,function(){
startMove(myDiv,'opacity',100);
});
});
}
myDiv.onmouseout = function(){
//注意動作執(zhí)行順序
startMove(this,'opacity',30,function(){
startMove(myDiv,'height',100,function(){
startMove(myDiv,'width',200);
});
});
}
}
getStyle = function(obj,attr){
if(obj.currentStyle){
//currentStyle IE瀏覽器
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
//getComputedStyle 第二個參數(shù)為垃圾參數(shù) 寫什么都可以 習(xí)慣false FF Chrome瀏覽器
}
同時運動
使用Json修改運動框架
startMove = function(obj,json,fn){
var flag = true;//假設(shè)所有運動都達到目標值的flag
clearInterval(obj.timer);
//開啟定時器前先關(guān)閉所有定時器
obj.timer = setInterval(function(){
for(var attr in json){
var icur = 0;
if(attr == 'opacity'){
icur = Math.round(parseFloat(getStyle(obj,attr))*100);
//如果是opacity則應(yīng)用parseFloat 之后×100是為了方便兼容alpha
//parseFloat取到的是多位小數(shù) 所以用Math.round四舍五入
}else{
icur = parseInt(getStyle(obj,attr));
}
var speed = (json[attr] -icur)/8;
speed = speed > 0?Math.ceil(speed):Math.floor(speed);
//緩沖運動 speed>0向上取整 speed<0向下取整
if(icur != json[attr]){
//如果不是所有的運動達到目標值
flag = false;
if(attr == 'opacity'){
obj.style.filter = 'alpha(opacity: '+(icur+speed)+')';
//針對 IE8 以及更早的版本
obj.style.opacity = (icur+speed)/100;
//針對FF Chrome
}else{
obj.style[attr] = icur + speed + "px";
}
}else{
//如果全部運動達到目標值蔓姚,關(guān)閉定時器
clearInterval(obj.timer);
if(fn){
fn(); //判斷是否需要執(zhí)行回調(diào)函數(shù)
}
}
}
},30)
}
var myDiv = document.getElementById("test");
myDiv.onmouseover = function(){
startMove(this,{width:400,height:400,opacity:100},function(){
alert("變換完成~");
});
}
myDiv.onmouseout = function(){
startMove(this,{opacity:30,height:100,width:200});
}