JavaScript(2):JS实现小女孩行走

JS实现小女孩行走

​ 用JS实现小女孩行走,行走的过程实际上就是图片不断移动的过程,把多张图片组合在一块儿,利用人眼反应速度没有图片更换速度快的原理,实现了小女孩行走。javascript

​ 基本思路是小女孩从浏览器最左边开始出现,每一个小女孩出现的高度位置是随机的,速度也是随机的。css

​ 实现起来并不难,但用到了js面向对象的思惟,下面经过代码方式来分析小女孩行走。html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<style type="text/css">
		.girl {
			position: absolute;
			/* 大小设置为小女孩的大小,不是整张图片的大小 */
			width: 79px;
			height: 108px;
			/* 设置整张背景图片 */
			background-image: url(img/girl.png);
			/* 定位到小女孩从左往右走的图片 */
			background-position: 0px -216px;
			left: 0px;
			top: 0px;
		}
	</style>
	<body>
		<div class="girl"></div>
	</body>
</html>

<script type="text/javascript">
	function Girl() {
    	//步子为0
		this.buzi = 0;
		//步长的随机1-10
		this.step = parseInt(Math.random() * 8 + 1);
		this.timer = null;
    	//小女孩都是从最终版出现
		this.left = 0;
		this.dom = null;
		// 浏览器高度
		this.maxTop = (document.documentElement.clientHeight || document.body.clientHeight) - 108;
    	//小女孩出现的高度
		this.top = parseInt(Math.random() * this.maxTop);
		this.dom = null;
		// 构造函数的调用方法
		this.init();
		//再调用行走的方法
		this.walk();
	}

	// 方法绑定到原型上面
	Girl.prototype.init = function() {
		// 添加一个元素,并添加到页面
		this.dom = document.createElement('div');
		// 添加类名
		this.dom.className = 'girl';
		// 设置不一样的top定位
		this.dom.style.top = this.top + 'px';
		// 添加到页面
		document.body.appendChild(this.dom);
	}

	// 行走的方法
	Girl.prototype.walk = function() {
		//桥接,这里的this赋值给一个变量
		var that = this;
		// 在定时器中用this是window,因此下把this保留下来,指向问题,每隔100毫秒走一步
		this.timer = setInterval(function() {
			//步子累加
			that.buzi++;
			//验证
			that.buzi = that.buzi > 7 ? 0 : that.buzi;

			that.left += that.step;
			if (that.left > 1200) {
				that.die();
			}
			// 设置当前元素的变化
			that.dom.style.backgroundPositionX = -79 * that.buzi + "px";
			that.dom.style.left = that.left + 'px';
		}, 100)
	}

	// 死亡的方法
	Girl.prototype.die = function() {
        //中止定时器
		clearInterval(this.timer);
        //移除这个div
		document.body.removeChild(this.dom)
	}
	
	//没隔500毫秒建立一个小女孩对象
	setInterval(function() {
		new Girl();
	}, 500)
</script>

效果:
在这里插入图片描述java

相关文章
相关标签/搜索