12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <!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>
- <!-- <img src="img/1.png" alt=""> -->
- <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;
- //图片距离左边的距离
- this.xLeft = Math.random() * (screenWidth - this.width)
- //距离顶部
- this.xTop = 0
- //图片路径
- this.bg = 'img/' + Math.floor(Math.random() * 4 + 1) + '.png'
- /*
- 如何让随机数为1,2,3,4整数
- Math.random() 0-1随机小数
- Math.random() * 4 0-4随机小数
- Math.random() * 4 + 1 1-5之间的随机小数 不包括5
- Math.floor() 向下取整 跟四舍五入没关系
- Math.floor(Math.random() * 4 + 1) 1,2,3,4
- */
- }
- // 原型下面写方法
- leaf.prototype.init = function(){
- //创建img标签
- 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)
- 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)
- }.bind(this),Math.random()*2000)
- // console.log(this)
- }
- var leafArr = []
- for (var i = 0; i < 20; i++) {
- //创建实例化对象
- var leaf1 = new leaf()
- leafArr.push(leaf1)
- leaf1.init()
- }
- document.onclick = function(){
- for(var i=0;i<leafArr.length;i++){
- leafArr[i].fall()
- }
- }
- </script>
- </body>
- </html>
|