jQuery 写评分星星效果

效果:

评分星星.png

html 部分:

<div class="container"></div>

css 部分:

<link rel="stylesheet" href="//at.alicdn.com/t/font_1743140_za6iztvtkw.css">
    <style>
        .star{
            font-size: 40px;
            color: orangered;
        }
    </style>

JS 部分:

    $(function () {

        // 初始化星星, 共5颗,3颗是实心的
        let range = 5, score = 3;

        for(let i = 0; i< range; i++){
            let star = $('<i/>').addClass('iconfont').addClass('star');   // 创建元素
            if (i < score){
                star.addClass('iconstar1')   // 分数显示实心星星
            }else{
                star.addClass('iconstar')   // 未达到的显示空心星星
            }
            $('.container').append(star);
        }

        // 鼠标移动选择评分
        let stars = $('.star');
        stars.mouseenter(function () {
            let index = $(this).index();
            stars.each(function (i) {
                if (i <= index){
                    $(this).addClass('iconstar1').removeClass('iconstar')
                }else{
                    $(this).addClass('iconstar').removeClass('iconstar1')
                }
            })
        });

        // 鼠标离开时显示初始的打分
        stars.mouseleave(function () {
            stars.each(function (i) {
                if(i < score){
                    $(this).addClass('iconstar1').removeClass('iconstar')
                }else{
                    $(this).addClass('iconstar').removeClass('iconstar1')
                }

            })
        });


        // 鼠标点击修改评分
        stars.click(function () {
            score = $(this).index() + 1
        })

    })

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。