123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- img{
- position: absolute;
- }
- </style>
- </head>
- <body>
- <script>
- //获取屏幕的宽度
- var screenWidth = document.body.clientWidth || document.documentElement.clientWidth
- //获取屏幕的高度
- var screenHeight = document.body.clientHeight || document.documentElement.clientHeight
- //构造函数 写属性
- function leaf(){
- this.width = Math.random() * 100 + 100
- //screenWidth - this.width 最大的距离
- this.xLeft = Math.random() * (screenWidth - this.width)
- this.xTop = 0
- //Math.random() 0->1 之间的随机小数
- //'img/1.png'
- // 1 - 4 随机整数
- //Math.random() * 4 0->4 之间的随机小数 不包括4
- //Math.random() * 4 + 1 1->5之间的随机小数 不包括5
- //Math.floor() 向下取整
- //Math.floor(Math.random() * 4 + 1) 1->5之间的随机小数向下取整 1 2 3 4
- this.bg = 'img/'+ Math.floor(Math.random() * 4 + 1) +'.png'
- }
- //原型下面 写方法
- //<img src="">
- leaf.prototype.init = function(){
- var oImg = document.createElement('img')
- oImg.src = this.bg
- oImg.style.width = this.width + 'px'
- oImg.style.left = this.xLeft + 'px'
- oImg.style.top = this.xTop + 'px'
- this.img = oImg
- document.body.appendChild(oImg)
- }
- //下落的方法
- leaf.prototype.fall = function(){
- setTimeout(function(){
- this.timer = setInterval(function(){
- console.log(this) //window .bind(this) this->leaf
- if(this.img.offsetTop < screenHeight - this.img.offsetHeight){
- this.img.style.top = this.img.offsetTop + 10 + 'px'
- } else{
- clearInterval(this.timer)
- }
- }.bind(this),20)
- // console.log(this) // window .bind(this) this-> leaf
- }.bind(this),Math.random()*2000)
- // console.log(this) // leaf
- }
- var leafArr = [];
- for(var i=0;i<20;i++){
- //创建实例化对象
- var leaf1 = new leaf()
- leaf1.init()
- leafArr.push(leaf1)
- }
- document.onclick = function(){
- for(var i=0;i<leafArr.length;i++){
- leafArr[i].fall()
- }
- }
- </script>
- </body>
- </html>
|