封装运动框架基本函数(多个属性包括透明度和zIndex)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style>
#demo{
width:100px;
height:100px;
background-color: pink;
border:1px solid black;
position:absolute;
top:50px;
left:100px;
/*opacity:0.2;*/
}
</style>
</head>
<body>
<button id="btn1">宽度高度都是300</button>
<button id="btn2">top改为200,left改为300</button>
<button id="btn3">宽度高度都是400,top left都是400,opacity改为0.6</button>
<div id="demo"></div>
</body>
</html>
<script>
function $id(id){return document.getElementById(id);}
var btn1=$id("btn1");
var btn2=$id("btn2");
var btn3=$id("btn3");
var demo=$id("demo");
var timer=null;
btn1.onclick=function () {
var json={width:300,height:300};
run(demo,json);
}
btn2.onclick=function () {
var json={top:200,left:300};
run(demo,json);
}
btn3.onclick=function () {
var json={width:400,height:400,top:400,left:400,opacity:60 ,zIndex:2};
run(demo,json);
}
function run(obj,json) {
clearInterval(obj.timer);
obj.timer=setInterval(function () {
var flag=true; //用来判断定时器是否停止,一定写在遍历的外面,否则一遍历就true
for(var attr in json)
{
var cstyle=0;
if(attr=="opacity")
{
cstyle= Math.round(parseInt(getStyle(obj,attr)*100)) || 0;
}
else{
cstyle=parseInt(getStyle(obj,attr)); //获得当前属性
}
var step=(json[attr]-cstyle)/10; //计算步长
step=step>0 ? Math.ceil(step) : Math.floor(step);
//判断透明度
if(attr=="opacity") // 判断用户有没有输入透明度
{
if("opacity" in obj.style) //判断浏览器支不支持opacity
{
obj.style.opacity=(cstyle+step)/100;
}
else
{
//obj.style.filter=alpha(opacity=30);
obj.style.filter="alpha(opacity="+(cstyle+step)*10+")";
}
}
//判断zIndex
else if(attr=="zIndex") //判断用户有没有输入zIndex
{
obj.style.zIndex=json[attr];
}
//不是opacity也不是zIndex的情况,加+"px"的属性
else{
obj.style[attr]=cstyle+step+"px";
}
if(cstyle!=json[attr]) //在遍历中,只要有一个属性值没到达目标位置,定时器就不能停
{
flag=false;
}
}
if(flag) //遍历完了之后,flag是true,所有的值都到达目标位置了,停止定时器,放在定时器里里面,每隔30毫秒可以判断一次是不是应该停止定时器了
{
clearInterval(obj.timer);
}
},30)
}
function getStyle(obj,attr) //返回谁的,哪个属性
{
if(obj.currrentStyle)
{
return obj.currentStyle[attr];
}
else{
return window.getComputedStyle(obj,null)[attr]; //w3c浏览器
}
}
</script>

点击上方的任意一个按钮,下面的盒子相应的做出动画效果,
关键代码: var json={width:400,height:400,top:400,left:400,opacity:60 ,zIndex:2};
run(demo,json);

浙公网安备 33010602011771号