十三、案例:气球类 发表于 2020-07-13 | 更新于: 2020-07-14 | 分类于 web前端 , JavsScript , JS进阶-04 | | 字数: 333 | 时长 ≈ 1 分钟十三、案例:气球类1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071<script> // 定义一个气球类 function Balloon(img){ // 容器属性 this.dom = document.createElement("div"); // 图片属性 this.img = img; // 图片的宽 this.width = this.img.width / 4; // 图片的高 this.height = this.img.height / 3; // 图片的定位X this.positionX = parseInt(Math.random() * 4); // 图片的定位Y this.positionY = parseInt(Math.random() * 3); // 定义left this.left = 0; // 定义top this.top = 0; // 设置样式的方法 this.setStyle = function(){ // 要使图片移动 需要设置绝对定位 this.dom.style.position = "absolute"; this.dom.style.left = this.left + "px"; this.dom.style.top = this.top + "px"; // 赋值dom的宽度和高度 this.dom.style.width = this.width + "px"; this.dom.style.height = this.height + "px"; // 设置元素的背景图片 this.dom.style.backgroundImage = "url(" + this.img.src + ")"; // 设置图片的背景定位 this.dom.style.backgroundPositionX = -this.width * this.positionX + "px"; this.dom.style.backgroundPositionY = -this.height * this.positionY + "px"; } // 上树 this.upTree = function(){ document.body.appendChild(this.dom); } // 设置初始化方法 this.init = function(){ this.upTree(); this.setStyle(); } // 图片移动方法 this.move = function(){ this.left += 10; this.dom.style.left = this.left + "px"; } // 执行init this.init(); } // 创建图片元素 var img = document.createElement("img"); // 设置路径 img.src = "images/balloon.jpg"; // 设置load事件 读完onload再执行代码 var b = null; // 定义定时器 var timer = null; img.onload = function(){ // 实例化对象 b = new Balloon(this); // 赋值timer timer = setInterval(function(){ b.move(); }, 200); }</script> 相关文章点击查看一、DOM十二、构造函数的四步十一、构造函数十、工厂模式的弊端九、滚动轮播图修改面向过程为面向对象八、面向对象三、贪吃蛇七、小钢琴六、尝试给div添加onkeydown事件五、tabIndex本文标题:十三、案例:气球类文章作者:Mango发布时间:2020年07月13日 - 23:21:02最后更新:2020年07月14日 - 13:27:10原始链接:https://mango185.github.io/post/2cc57d2.html 许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。-------------------本文结束 感谢您的阅读-------------------