创建Move.js运动框架
function getStyle(obj,name){
if (obj.currentStyle) {
return obj.currentStyle[name];//ie
} else{
return getComputedStyle(obj,false)[name];//ff
}
}
//任意值的运动框架
var timer=null;
function startMove(obj,json,fnEnd){
//停止上一次计数器,解决同个对象同事调用多个startMove时定时器叠加问题;
clearInterval(obj.timer);
obj.timer=setInterval(function(){
//判断同时运动
var bStop=true;//假设值都到了
for (var attr in json) {
//取当前值,用于存储attr的属性值
var cur =0;
if(attr=='opacity'){
cur=Math.round(parseFloat(getStyle(obj,attr))*100);//ie
}else{
cur=parseInt(getStyle(obj,attr));//ff
}
//计算速度
var speed=(json[attr]-cur)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);//取整,解决浏览器忽略小于1px导致运动结束时离目标值少几个px的距离
//判断是否同时到达
if (cur!=json[attr]) {
bStop=false;
}
if(attr=='opacity'){
obj.style.filter='alpha(opcity:'+(cur+speed)+')';
obj.style.opacity=(cur+speed)/100;
}else{
obj.style[attr]=cur+speed+"px";
}
}
if(bStop){
clearInterval(obj.timer);
if(fnEnd)fnEnd();
}
},30);
}
在html页面应用框架进行运动
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div1{width: 100px;height: 100px;background: red;opacity: 0.3;
filter: alpha(opacity:30); }
</style>
<script type="text/javascript" src="js/Move.js" ></script>
<script>
window.οnlοad=function(){
var btn=document.getElementById('btn');
var div1=document.getElementById('div1');
btn.οnclick=function(){
startMove(div1,{width:101,height:300,opacity:100});//输入你想要div进行运动的属性
}
}
</script>
</head>
<body>
<input type="button" id="btn" value="运动" />
<div id="div1"></div>
</body>
</html>