码迷,mamicode.com
首页 > 其他好文 > 详细

如何用面对对象来做一个躁动的小球?

时间:2017-06-19 22:11:16      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:window   pen   this   blog   set   win   end   absolute   size   

  今天来看看怎样用面对对象来做一个躁动的小球。

  首先我们先创建一个对象,他的属性包含小球的随机水平、纵向坐标,随机宽、高,随机颜色,以及创建小球的方法。

 

html:
<div id="wrap"></div>

js:

function Boll(x,y,w,h,color){
// 随机宽高 var wh = randFn(5, 40); // 随机颜色 var c = rgb(+randFn(0, 255)+, + randFn(0,255)+,+randFn(0, 255)+); // 随机x坐标 水平位置 document.body.clientWidth 网页可见区域的宽 this.x = randFn(0, document.body.clientWidth - 20); // 随机y坐标 纵向位置 document.body.clientHeight 网页可见区域的高 this.y = randFn(0, document.body.clientHeight - 20); // 随机颜色 this.color = c; // 随机宽高 this.w = wh; this.h = wh; // 小球展示出来 this.show = function(){ //创建小球 var bolDiv = document.createElement("div"); bolDiv.style.background = this.color; bolDiv.style.left = this.x + "px"; bolDiv.style.top = this.y + "px"; bolDiv.style.width = this.w + "px"; bolDiv.style.height = this.h + "px"; // 把创建出来的小球插入到wrap里面 var wrap = document.getElementById("wrap"); wrap.appendChild(bolDiv); } }

 

之后把小球添加在页面上,设定计时器来让小随机出现。

js: 

//添加小球到页面上 var fuc = function(){ // 创建小球对象 var bol = new Boll(); //设置小球相关数据 位置 宽高 并添加 bol.show() } //间隔性计时器 每隔一秒执行一次fuc函数 即创建小球对像并添加到页面上 window.setInterval(fuc,1000)

 

创建小球还是少不了style:

*{
            margin: 0px;
            padding: 0px;
        }
        html,body{
            width: 100%;
            height: 100%;

        }
        #wrap{
            width: 100%;
            height: 100%;
            background: black;
            position: relative;
        }
        #wrap div{
            position: absolute;
            border-radius: 50%;
        }

 

 

如何用面对对象来做一个躁动的小球?

标签:window   pen   this   blog   set   win   end   absolute   size   

原文地址:http://www.cnblogs.com/yhyanjin/p/7050470.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!