附上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
width: 100px;
height: 100px;
position: absolute;
background: lightcoral;
border-radius: 50%;
}
</style>
</head>
<body>
<script>
var arrX = [];
var arrY = [];
var i = 0;
var stop;
function Ball() {}
Ball.prototype = {
ball:null,
createBall: function () {
this.ball = document.createElement("div");
document.body.appendChild(this.ball);
this.ball.className = "box";
this.ball.self = this;
this.ball.addEventListener("mousedown", this.mouseHandler);
return this.ball;
},
mouseHandler: function (e) {
if (e.type === "mousedown") {
this.addEventListener("mouseup", this.self.mouseHandler);
document.ball = this;
document.boxObj = {
x: e.offsetX,
y: e.offsetY
};
document.addEventListener("mousemove", this.self.mouseHandler);
} else if (e.type === "mousemove") {
this.ball.style.left = e.x - this.boxObj.x + "px";
this.ball.style.top = e.y - this.boxObj.y + "px";
arrX.push(this.ball.style.left);
arrY.push(this.ball.style.top);
} else if (e.type === "mouseup") {
this.removeEventListener("mouseHandler", this.self.mouseHandler);
document.removeEventListener("mousemove", this.self.mouseHandler);
document.self = this;
i = arrX.length;
stop = setInterval(this.self.autoMove, 16);
}
},
autoMove: function () {
document.self.style.left = arrX[i];
document.self.style.top = arrY[i];
if (i <= 0) {
arrX.length = 0;
arrY.length = 0;
clearInterval(stop);
return;
}
i--;
}
};
var ball = new Ball();
ball.createBall();
</script>
</body>
</html>