JS实现星级评分

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style type="text/css">
        td
        {
            width:50px;
            height:50px;
            border:1px solid #808080;
            cursor:pointer;
        }
    </style>
    <script type="text/javascript">
        window.onload=function()
        {
            var tds = document.getElementsByTagName("td");
            
            for(var i=0;i<tds.length;i++)
            {
               
                tds[i].onmouseenter = OnMouseEnter;
                tds[i].onmouseleave = OnMouseLeave;
                tds[i].onclick = OnClick;

            }
        }
        //判断是否被点击,是 就保存黄色;不是 就变为白色
        var isClick = false;

        //鼠标点击td保留背景色
        function OnClick()
        {
            if (!isClick)
            {
                OnMouseEnter;
                isClick = true;
            }
        }

        //鼠标停留td背景色变黄
        function OnMouseEnter()
        {
            var previous = this.previousElementSibling;
            this.style.backgroundColor = "yellow";
            while (previous)
            {
                previous.style.backgroundColor = "yellow";
                previous = previous.previousElementSibling;
            }
            
        }
        //鼠标移开td背景色变白
        function OnMouseLeave()
        {
            if (!isClick)
            {
                var previous = this.previousElementSibling;
                this.style.backgroundColor = "white";
                while (previous) {
                    previous.style.backgroundColor = "white";
                    previous = previous.previousElementSibling;
                }
            }
        }

    </script>
</head>
<body>
    <div style="text-align:center;">
        <table style="margin:0 auto;">
            <thead>
                评分后不可更改
            </thead>
            <tr>
                <td>1</td>
                <td>2</td>
                <td>3</td>
                <td>4</td>
                <td>5</td>
            </tr>
        </table>
    </div>
</body>
</html>

鼠标点击后可保留颜色。

页面效果如下:

原文地址:https://www.cnblogs.com/miaoying/p/5280547.html