案例:随机小方块

产生随机数对象,自调用构造函数

产生小方块对象,自调用构造函数,里面存放:
食物的构造函数
给原型对象添加方法:初始化小方块的显示的效果及位置---显示地图上
给原型对象添加方法,产生随机位置
实例化对象
 
<!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<title>title</title>
<style>
.map {
width: 800px;
height: 600px;
background-color: #CCC;
position: relative;
}
</style>
</head> <body>
<div class="map" id="dv"></div>
<script src="common.js"></script>
<script>
//产生随机数对象的 (function (window) {
function Random() {
};
Random.prototype.getRandom = function (min, max) {
return Math.floor(Math.random() * (max - min) + min);
};
window.Random = new Random;
})(window); //自调用构造函数的方式, 分号一定要加上 //产生小方块对象
(function (window) {
var map = document.querySelector(".map");
//食物的构造函数
function Food(width, height, color) {
this.width = width || 20;
this.height = height || 20;
//横坐标,纵坐标
this.x = 0;//横坐标随机产生的
this.y = 0;//纵坐标随机产生的
this.color = color;//小方块的背景颜色
this.element = document.createElement("div");
}
//初始化小方块的显示的效果及位置---显示地图上
Food.prototype.init = function (map) {
//设置小方块的样式
var div = this.element;
div.style.position = "absolute";//脱离文档流
div.style.width = this.width + "px";
div.style.height = this.height + "px";
div.style.backgroundColor = this.color;
//把小方块加到map地图中
map.appendChild(div);
this.render(map);
};
//产生随机位置
Food.prototype.render = function (map) {
//随机产生横纵坐标
var x = Random.getRandom(0, map.offsetWidth / this.width) * this.width;
var y = Random.getRandom(0, map.offsetHeight / this.height) * this.height;
this.x = x;
this.y = y;
var div = this.element;
div.style.left = this.x + "px";
div.style.top = this.y + "px";
};
//实例化对象
var fd = new Food(20, 20, "green");
fd.init(map);
console.log(fd.x + "=====" + fd.y);
})(window);
</script>
</body> </html>

最新文章

  1. CentOS 7.0 使用 yum 安装 MariaDB 与 MariaDB 的简单配置
  2. [WCF编程]8.服务实例的生命周期
  3. js的一点
  4. node.js处理post请求
  5. 【BZOJ 1503】【NOI 2004】郁闷的出纳员
  6. Apache Mina(一)
  7. 怒刷DP之 HDU 1024
  8. BZOJ 1717: [Usaco2006 Dec]Milk Patterns 产奶的模式
  9. Oracle 导入本地dmp文件 详细操作步骤
  10. nodejs安装:nodejs入门
  11. 怎样把人物处理的清晰PS教程
  12. 一个普通的 Zepto 源码分析(三) - event 模块
  13. web前端工程师全套教程免费分享
  14. window10下的eclipse用java连接hadoop执行mapreduce任务
  15. mongoDB之数据类型
  16. C++课程设计类作业2
  17. Springmvc 中org.springframework.http.converter.json.MappingJackson2HttpMessageConverter依赖jackson包
  18. A Problem-Solving FlowChart || 如何解决编程问题
  19. drf图片字段序列化完整路径
  20. vs2008编译openssl,静态库/动态库,批处理

热门文章

  1. JNA 使用总结
  2. Longest Ordered Subsequence POJ - 2533 dp 最长上升/不下降 子序列
  3. vjudge 棋盘
  4. 洛谷 P3796 【模板】AC自动机(加强版)(AC自动机)
  5. 回环屏障CyclicBarrier
  6. Codeforces Round #601 (Div. 2) C League of Leesins
  7. 【PAT甲级】1115 Counting Nodes in a BST (30分)(二叉查找树)
  8. Mahmoud and Ehab and the message
  9. 利用python装饰器为字符串添加,HTML标签
  10. spring的IOC过程剖析