星级评分(全星)

想法是,一张empty.png(空心的星),一张full.png(实心的星),然后onmouse事件切换

html

<div id="content"></div>  <!--星是动态插入的-->

css

#content{
    width: 500px;
    height: 200px;
    border: 1px solid grey;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;
}
.star{
    width: 50px;
    height: 50px;
    margin: 5px;
    background: url(empty.png) no-repeat;
}

js

  • 想试着用面对对象思想去写
    //动态添加星
    var addStar = function(){
        for(let i = 0; i < num; i++){
            let div = document.createElement('div')
            div.className = 'star'
            document.getElementById("content").appendChild(div)
        }
    }


    var Star = function(){
        //以一个类封装所有的属性和方法
        var o = {}

        o.starList = document.getElementsByClassName('star')

        o.flag = true
        
        //清除实心
        o.clearStar = function(){
            for(let i = 0; i < num; i++){
                o.starList[i].style.backgroundImage = "url('empty.png')"
            }
        }

        //鼠标移动到星上 & flag == tre
        o.onMouse = function(i){
            if(o.flag){
                for(let j = 0; j <= i; j++){
                    o.starList[j].style.backgroundImage = "url('full.png')"
                }
            }
        }

        //鼠标移出星 & flag == true
        o.offMouse = function(i){
            if(o.flag){
                for(let j = 0; j <= i; j++){
                    o.starList[j].style.backgroundImage = "url('empty.png')"
                }
            }
        }

        //点击星(将flag设为false就不会触发onmouseout事件
        o.onClick = function(i){
            o.flag = false
            o.clearStar()
            for(let j = 0; j <= i; j++){
                o.starList[j].style.backgroundImage = "url('full.png')"
            }
        }

        return o //返回这个类

    }


    //主函数  do thing
    var __main = function(){

        addStar()
        var star = Star()

        for(let i = 0; i < num; i++){
            star.starList[i].onmouseover = function(){
                star.onMouse(i)
            }
            star.starList[i].onmouseout = function(){
                star.offMouse(i)
            }
            star.starList[i].onclick = function(){
                star.onClick(i)
            }
        }

    }

    const num = 5  //五颗星
    __main()
    

猜你喜欢

转载自www.cnblogs.com/wulzt/p/9326549.html