1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <!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
- //图片位置
- this.xLeft = Math.random() * (screenWidth - this.width)
- //距离顶部
- this.xTop = 0
- //图片的路径
- //img/1.png
- 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)
- setTimeout(function () {
- console.log(this)
- //一直下落的时间
- this.timer = setInterval(function () {
- 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>
|