十三、案例:气球类

十三、案例:气球类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<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>

Uldf3R.png

点击查看

本文标题:十三、案例:气球类

文章作者:Mango

发布时间:2020年07月13日 - 23:21:02

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/2cc57d2.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------