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 = 100 + 100 * Math.random()
- //图片位置
- this.xLeft = (screenWidth - this.width) * Math.random()
- //距离顶部
- this.xTop = 0
- //图片路径
- //<img src="./img/1.png" alt="">
- /*
- Math.random() (0-1)
- Math.random() * 4 (0-4)
- Math.random() * 4 + 1 (1-5)
- Math.floor(Math.random() * 4 + 1) [1,2,3,4]
- */
- this.bg = 'img/' + Math.floor(Math.random() * 4 + 1) + '.png'
- }
- //原型对象下面写方法
- 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'
- document.body.appendChild(oImg)
- this.img = oImg
- }
- //下落的方法
- leaf.prototype.fall = function () {
- // console.log(this) //leaf
- setTimeout(function () {
- // console.log(this)//leaf
- 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)
- }.bind(this), Math.random() * 2000)
- }
- 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>
|