#box{
position: absolute;
width: 120px;
height: 120px;
line-height: 120px;
background-color: red;
color: #ffffff;
border-radius: 50%;
text-align: center;
}
function animate(obj,option){
obj.timer = setInterval(function(){
var flag = true;
for(var k in option){
var leader =parseInt(getStyle(obj,k)) || 0; //获取指定元素挡墙的属性值
var target = option[k]; //获取指定元素目标属性值
var step = (target - leader) / 10; //计算每次移动的步长
step = step > 0 ? Math.ceil(step): Math.floor(step);
leader = leader + step; //计算属性值
obj.style[k] = leader + "px"; //设置属性值
if(leader != target){
flag = false;
}
}
if(flag){ //移动完后清除定时器
clearInterval(obj,timer);
}
},15);
}
function getStyle(obj,attr){
if(window.getComputedStyle){
return window.getComputedStyle(obj,null)[attr];
}
else{
return obj.currentStyle[attr];
}
}
var obj = document.getElementById('box');
obj.onclick = function(){
animate(obj,{'left':500,'top':200})
}
一键复制
编辑
Web IDE
原始数据
按行查看
历史