JavaScript(2):JS实现小女孩行走 您所在的位置:网站首页 行走的小人gif动图 JavaScript(2):JS实现小女孩行走

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

2023-10-26 13:29| 来源: 网络整理| 查看: 265

JS实现小女孩行走

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

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

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

.girl { position: absolute; /* 大小设置为小女孩的大小,不是整张图片的大小 */ width: 79px; height: 108px; /* 设置整张背景图片 */ background-image: url(img/girl.png); /* 定位到小女孩从左往右走的图片 */ background-position: 0px -216px; left: 0px; top: 0px; } 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)

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



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有