1. 程式人生 > >面向物件-小球運動及大小操作

面向物件-小球運動及大小操作

好好學習 ,天天向上。Are you ready?在這裡插入圖片描述

話不多說,程式碼奉上。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
	</head>
	<body>
		<button>按鈕</button>
		<script>
			function Ball(r) {
				if (r) {
					//                this是new 出來的物件
					this.r = r;
				}
			}

			Ball.prototype = {
				_r: 25,
				set r(value) {
					this._r = value;
					if (!this.ball) return;
					this.ball.style.width = value * 2 + "px";
					this.ball.style.height = value * 2 + "px";
					this.ball.style.borderRadius = value + "px";
				},
				get r() {
					return this._r;
				},
				ball: null,
				bool: false,
				createBall: function(parent) {
					if (!this.ball) {
						this.ball = document.createElement("div");
						this.ball.style.width = this.r * 2 + "px";
						this.ball.style.height = this.r * 2 + "px";
						this.ball.style.borderRadius = this.r + "px";
						this.ball.style.backgroundColor = "red";
						this.ball.style.position = "absolute";
						this.ball.self = this;
						this.ball.addEventListener("click", this.clickHandler);
						parent.appendChild(this.ball);
					}
					return this.ball;
				},
				clickHandler: function(e) {
					this.self.bool = !this.self.bool;
				},
				update: function() {
					if (!this.bool) return;
					this.ball.style.left = this.ball.offsetLeft + 2 + "px";
				}

			};
			var b1 = new Ball(20);
			b1.createBall(document.body);
			var bn = document.querySelector("button");
			bn.addEventListener("click", clickHandler);

			function clickHandler(e) {
				b1.r = b1.r + 10;
			}
			var arr = [];
// 			for (var i = 0; i < 10; i++) {
// 				var b1 = new Ball(20);
				b1.createBall(document.body);
				arr.push(b1);
			// }


			animation();

			function animation() {
				requestAnimationFrame(animation);
// 				for (var i = 0; i < arr.length; i++) {
// 					arr[i].update();
// 				}
				b1.update();
			}
		</script>
	</body>
</html>