面向对象-小球运动及大小操作

好好学习 ,天天向上。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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值