JS实现简单的评分评星功能

时间:2020-12-26 05:45:19
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box {
            list-style: none;
            height: 28px;
            width: 135px;
            /*清除浮动*/  overflow: hidden;
        }

        .image {
            height: 28px;
            width: 27px;
            float: left;
            background: url(https://img-blog.csdn.net/20170111195511514?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXlkcmVhbWhvcGU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center) no-repeat;
        }

        .imageOne {
            height: 28px;
            width: 27px;
            float: left;
            /*background-position: 0 -28px*/  background: url(https://img-blog.csdn.net/20170111195511514?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbXlkcmVhbWhvcGU=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center) no-repeat 0 -28px;

        }

    </style>
    <script>
        window.onload = function () {
            var box = document.getElementById("box");
            var images = box.getElementsByTagName("li");
            var info = document.getElementById('info');
            var starshow = 0;
            // 循环遍历每个星星  for (var i = 0; i < images.length; i++) {
                images[i].onmouseover = (function (num) {
                    return function () {
                        //再遍历一次所有的星鼠标左边的星变成黄色,有边变成灰色  for (var j = 0; j < images.length; j++) {
                            if (j <= num) {
                                //黄色五角星添加类名imageOne  images[j].className = "imageOne";
                            } else {
                                images[j].className = "image";
                            }
                        }
                    }
                }(i));//立即调用,把i传给num  images[i].onmouseup = (function (i) {
                    return function () {
                        starshow = 1+i;
                        info.innerHTML = '你打了'+starshow+'分!'  }
                }(i));
            }
        }

    </script>
</head>
<body>
<ul id="box">
    <li class="image"></li>
    <li class="image"></li>
    <li class="image"></li>
    <li class="image"></li>
    <li class="image"></li>

</ul>
<div id="info"></div>
</body>
</html>