12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <style>
- img {
- position: absolute;
-
- }
- </style>
- <script>
- // scrollTop scrollLeft
- // 1.获取屏幕可视宽高
- var screenWidth = document.documentElement.clientWidth || document.body.clientWidth;
- var screenHeight = document.documentElement.clientHeight || document.body.clientHeight;
- console.log(screenWidth,screenHeight)
- // 2.构造函数属性
- function Leaf() {
- // 定义图片宽度
- this.width = Math.round(Math.random() * 100 + 100);
- // 图片距离顶部位置
- this.tops = 0;
- // 图片距离左侧位置
- this.newLeft = Math.random() * (screenWidth - this.width);
- // 图片引入 ./img/3.png
- // Math.random()* y-x + x
- // Math.round(Math.random() * 3 + 1)
- this.newImg = "./img/" + Math.floor(Math.random() * 4 + 1) + '.png'
- }
- // new Leaf();
- Leaf.prototype.init = function() {
- // 创建图片标签
- var imgs = document.createElement("img");
- // 图片路径
- imgs.src = this.newImg;
- // 图片距离顶部位置
- imgs.style.top = this.tops + "px";
- // 图片距离左侧位置
- imgs.style.left = this.newLeft + "px";
- // 图片宽度
- imgs.style.width = this.width + "px";
- this.img = imgs;
- // console.log(this.img)
- document.body.appendChild(imgs);
- }
- //页面渲染树叶
- var newArr = [];
- for(var i = 0; i <20;i++) {
- var newLeaf = new Leaf();
- newLeaf.init();
- newArr.push(newLeaf);
- }
- // 树叶下落
- // 箭头函数
- // 没有this指向 this当前项
- Leaf.prototype.fail = function() {
- setTimeout(function(){
- var timer = setInterval(function(){
- if(this.img.offsetTop < screenHeight - this.img.offsetHeight){
- this.img.style.top = this.img.offsetTop + 10 + 'px';
- } else {
- clearInterval(timer)
- }
- }.bind(this),30);
- }.bind(this),Math.random()*3000)
- }
- // 点击图片树叶下落
- document.onclick = function() {
- for(var i=0;i<newArr.length;i++) {
- newArr[i].fail();
- }
- }
- </script>
- </body>
- </html>
|