2.class案例(随机色卡)——ES6类和继承

功能
1.页面加载成功后,会随机的出现一定数量的div
2.div的大小,color,position随机
3.鼠标悬停时,div变大,并浮动到最前面

Card.js

class Card{
    //构造函数
    /*
        x:横坐标
        y:纵坐标
    */

    constructor(x,y,width,height,color){
        //创建div元素
        this.element = document.createElement('div');
        this.element.style.postion = 'absolute';
        this.element.style.top = y + 'px';
        this.element.style.left = x + 'px';
        this.element.style.width = width + 'px';
        this.element.style.height = height + 'px';
        this.element.style.backgroundColor = color;
    }

    //鼠标悬停特效
    show(){
        (this.element.style.width += 20) + 'px'
        (this.element.style.height += 20) + 'px'
        this.element.style.zIndex = Card.i++;
    }

    //加载到页面
    render(){
        //使用箭头函数,不会影响this指向
        this.element.onmouseov = ()=>{
            this.show();
        }
        document.body.appendChild(this.element)
    }
}

index.js

window.onload = function(){

    const colorList = ['red','yellow','blue','orange','pink','green'];
    //定义一个静态的属性,所有实例共享
    Card.i = 0;
    for(let i=0;i<30;i++){
        //初始化每一块色卡的属性
        let width = ParseInt(Math.randow()*100)+80;
        let heigth = ParseInt(Math.randow()*100)+80;
        let x = ParseInt(Math.randow()*(document.documentElement.clientWidth-width));
        let y = ParseInt(Math.randow()*(document.documentElement.clientHeight-height));
        let color = colorList[ParseInt(Math.randow()*colorList.length)];
        let temp = new Card(x,y,width,height,color);
        temp.render();
    }

}

使用继承方法扩展Card类

RoundCard.js

class RoundCard extend Card{
    constructor(x,y,width,height,color){
        super(x,y,width,height,color);
        this.element.style.borderRadius = 20+'px';
    }

    //重写父类show方法
    show(){
        super.show();
        this.element.style.border = '1px solid blue';
    }

    render(){
        super.render();
        this.element.onmouseout = ()=>{
            this.element.remove();
        } 
    }
}

index.js

window.onload = function(){

    const colorList = ['red','yellow','blue','orange','pink','green'];
    //定义一个静态的属性,所有实例共享
    Card.i = 0;
    for(let i=0;i<30;i++){
        //初始化每一块色卡的属性
        let width = ParseInt(Math.randow()*100)+80;
        let heigth = ParseInt(Math.randow()*100)+80;
        let x = ParseInt(Math.randow()*(document.documentElement.clientWidth-width));
        let y = ParseInt(Math.randow()*(document.documentElement.clientHeight-height));
        let color = colorList[ParseInt(Math.randow()*colorList.length)];
        let temp;
        if(i%2==0){
            temp = new Card(x,y,width,height,color);
        }else{
            temp = new RoundCard(x,y,width,height,color);
        }
        
        temp.render();
    }

}
原文地址:https://www.cnblogs.com/lisa2544/p/15666778.html