0
点赞
收藏
分享

微信扫一扫

前端_星级评分效果

mjjackey 2022-02-19 阅读 62
前端

效果展示


实现代码 

style部分

    body {
      margin: 0;
      padding: 0;
    }

    #starBox {
      height: 20px;
      width: 130px;
    }

    #starBox em {
      float: left;
      width: 26px;
      height: 20px;
      background: url(star.png) 0 -20px no-repeat;
    }

    #starNotice {
      font: 12px;
      width: 130px;
      text-align: center;
      margin-top: 5px;
      cursor: pointer;
    }

html部分 

  <div id="starBox">
    <em></em>
    <em></em>
    <em></em>
    <em></em>
    <em></em>
  </div>
  <p id="starNotice"></p>

js部分 

    window.onload = function () {
      var star = document.getElementsByTagName('em');
      var temp = 0;
      var temp1 = 0;

      for (var i = 0, len = star.length; i < len; i++) {
        star[i].index = i;

        document.getElementById('starBox').onmouseout = function () {
          if (temp) return
          document.getElementById('starNotice').style.display = 'none'
        }
        document.getElementById('starBox').onmouseover = function () {
          document.getElementById('starNotice').style.display = 'block'
        }

        // 鼠标经过
        star[i].onmouseover = function () {
          if (temp) return
          clear();
          for (var j = 0; j < this.index + 1; j++) {
            star[j].style.backgroundPosition = '0 0';
            temp1 = this.index + 1;
            document.getElementById('starNotice').innerHTML = temp1 + ' 颗星';
          }
        }

        // 鼠标移出
        star[i].onmouseout = function () {
          if (temp) return
          for (var j = 0; j < this.index + 1; j++) {
            star[j].style.backgroundPosition = '0 -20px';
            temp1 = this.index + 1;
            document.getElementById('starNotice').innerHTML = temp1 + ' 颗星';
          }
          current(temp);
        }

        // 点击后
        star[i].onclick = function () {
          if (temp) return
          temp = this.index + 1;
          document.getElementById('starNotice').innerHTML = temp + ' 颗星';
          current(temp);
        }
      }

      //清除所有
      function clear() {
        for (var i = 0, len = star.length; i < len; i++) {
          star[i].style.backgroundPosition = '0 -20px';
        }
      }
      //显示当前第几颗星
      function current(temp) {
        for (var i = 0; i < temp; i++) {
          star[i].style.backgroundPosition = '0 0';
        }
      }
    }

sprite图 

  

举报

相关推荐

0 条评论