附上代碼:
<!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 = [];//新建數組,記錄小球的x軸路徑
var arrY = [];//新建數組,記錄小球的y軸路徑
var i = 0;//小球移動時數組的第i項存進數組
var stop;//小球的運動
function Ball() {}//新建小球類
Ball.prototype = {
ball:null,//新建小球
createBall: function () {//建立小球,添加到body中
this.ball = document.createElement("div");
document.body.appendChild(this.ball);
this.ball.className = "box";
this.ball.self = this;//引入小球的屬性self指向Ball對象(this)
this.ball.addEventListener("mousedown", this.mouseHandler);//添加點擊事件
return this.ball;
},
mouseHandler: function (e) {
if (e.type === "mousedown") {//當鼠標點擊時添加移動事件給document,添加鼠標鬆開事件給小球,而且使用回調,每次執行一個函數,對e.type進行判斷
this.addEventListener("mouseup", this.self.mouseHandler);
document.ball = this;//引入對象ball給document
document.boxObj = {//給document添加對象屬性鼠標相對小球位置
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 () {//返回函數,當小球運動到初始狀態時,取消Interval函數
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>