<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 50px;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function() {
animate(box,"left",500);
}
btn400.onclick = function() {
animate(box,"top",400);
}
// 封装单个属性的运动框架
function animate(obj,attr,target) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var current = parseInt(getStyle(obj,attr));
var step = ( target -current ) / 10; //步长
step = step > 0 ? Math.ceil(step) : Math.floor(step);
obj.style[attr] = current + step + "px";
if(current == target )
{
clearInterval(obj.timer);
}
} ,30)
}
//兼容性处理
function getStyle(obj,attr) {
if(obj.currentStyle)
{
return obj.currentStyle[attr];
}
else
{
return window.getComputedStyle(obj,null)[attr];
}
}
</script>
封装单个属性的运动框架
最新推荐文章于 2022-07-15 08:29:13 发布