面向对象编写--模拟下雪

CSS部分

    <style>
        * {
            margin: 0;
            padding: 0;
        }
        #box {
            width: 1000px;
            height: 600px;
            background: #000000;
            border: 5px solid red;
            margin: 20px auto;
            position: relative;
        }
    </style>

HTML部分

    <div id="box"></div>

JS部分

<script>
    /*
     1、确定构造函数  Snow
     2、确定属性  动态创建的雪花img   雪花容器
     3、确定功能   入口功能(雪花的创建)   雪花移动
     */
    window.onload = function(){
        setInterval(function(){
            return new Snow().init().move();
        },1000)
    }

     //确定构造函数
    function Snow(){
        //设置属性,动态创建雪花,雪花的容器
        this.img = create('img');
        this.box = $id('box');
    }
    //设置原型功能
    Snow.prototype = {
        init : function(){
            //设置雪花的路径
            this.img.src = "./snow.png";
            //把雪花添加到div中去
            this.box.appendChild(this.img);
            //给雪花设置定位
            this.img.style.position = "absolute";
            //设置雪花的大小
            this.img.width = this.img.height = rand(10,27);
            //设置雪花的边界值
            this.img.style.left = rand(0,this.box.offsetWidth - this.img.offsetWidth) + "px";
            this.img.style.top = 0;
            return this;   //该方法返回new出来的对象
        },
        move : function(){
            //为每一个雪花定义速度
            this.speedX = -rand(1,5);
            this.speedY = rand(1,5);
            //为每一个雪花创建一个定时器,保证雪花运动的定时器是独立的
            this.timer = setInterval(function(){
                //设置运动
                this.img.style.left = this.img.offsetLeft + this.speedX + "px";
                this.img.style.top = this.img.offsetTop + this.speedY + "px";
                //设置运动边界
                if(this.img.offsetLeft < 0 || this.img.offsetTop > this.box.offsetHeight){
                    this.img.remove();
                    clearInterval(timer);
                }
            }.bind(this),60);
        }
    }
    //获取页面元素
    function $id(id){
        return document.getElementById(id)
    }
    //动态创建页面元素
    function create(ele){
        return document.createElement(ele)
    }
    //获取任意区间的整数值
    function rand(min,max){
        return Math.round(Math.random() * (max-min) + min);
    }
</script>
原文地址:https://www.cnblogs.com/self-hard/p/10367024.html