<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: absolute;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
<script src="./animate.js"></script>
<script>
const animate = new XAnimate()
animate.getEle(‘.box‘)
animate.setOptions({
position: {
y: 700
},
finished: function() {
this.element.style.backgroundColor = ‘skyblue‘
}
})
animate.start()
</script>
</body>
</html>
/**
* author: Mr Lee (James)
* description: a simple function to realize animation
* date: 2020-8-23 10:46
* version: 1.0
* site: https://www.cnblogs.com/Mr-O-o-Lee/
*/
function XAnimate() {
// 创建一个构造器
function Xconstructor() {
// 移动的元素
this.element = null
// 移动的位置
this.position = {
x: 0,
y: 0
}
// 动画成功后的回调
this.callBack = null
return this
}
// 获取DOM对象
Xconstructor.prototype.getEle = function (ele) {
this.element = document.querySelector(ele)
}
// 属性配置
Xconstructor.prototype.setOptions = function (options) {
Object.assign(this.position, options.position)
this.callBack = options.finished
}
// 动画函数
Xconstructor.prototype.move = function () {
var targetX = this.position.x
var targetY = this.position.y
var ele = this.element
//获取每次移动的距离
function getStep(axis, that) {
// 每次移动的距离
var strategy = {
x: (targetX - that.element.offsetLeft) / 10,
y: (targetY - that.element.offsetTop) / 10
}
var pickUp = strategy[axis.toLowerCase()]
return pickUp > 0 ? Math.ceil(pickUp) : Math.floor(pickUp)
}
function moveItem() {
// 获取每次移动的距离
var stepX = getStep(‘x‘, this)
var stepY = getStep(‘y‘, this)
console.log(stepX)
console.log(stepY)
if (ele.offsetLeft == targetX && ele.offsetTop == targetY) {
clearInterval(this.timer);
this.callBack && this.callBack()
}
ele.style.left = ele.offsetLeft + stepX + ‘px‘
ele.style.top = ele.offsetTop + stepY + ‘px‘
}
// 每个15ms移动一次位置,很耗性能
this.timer = setInterval(moveItem.bind(this), 15)
}
Xconstructor.prototype.start = function () {
this.move()
console.info(this)
}
// 调用构造器初始化一个对象,并返回
return new Xconstructor()
}
原文:https://www.cnblogs.com/Mr-O-o-Lee/p/13548534.html