原生JavaScript的评分星星

思路:

        1.排列五颗星星,第一颗默认就是实心,其他为空心。

        2.当鼠标移入到星星的时候判断当前星星的下标,移入的星星包含之前的星星都变为实心

        3.当点击提交按钮时弹出评的分数

        4.图标我是去阿里图标库下载的

鼠标移入星星会变实心:

点击会输出分数:

下面是完整的代码:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .star {
      width: 200px;
      height: 50px;
      display: flex;
      justify-content: space-around;
      align-items: center;
      margin: 50px auto;
    }

    .star span {
      width: 30px;
      height: 30px;
      display: inline-block;
      cursor: pointer;
    }

    .on {
      background: no-repeat url('./star.png');
      background-size: 30px 30px;
    }

    .off {
      background: no-repeat url('./starNull.png');
      background-size: 30px 30px;
    }

    #btn {
      width: 100px;
      height: 40px;
      background-color: chocolate;
      text-align: center;
      line-height: 40px;
      color: #ffffff;
      margin: 0 auto;
      cursor: pointer;
    }
  </style>
</head>

<body>
  <div class="star">
    <span class="star_item on"></span>
    <span class="star_item off"></span>
    <span class="star_item off"></span>
    <span class="star_item off"></span>
    <span class="star_item off"></span>
  </div>
  <div id="btn">提交</div>

  <script>
    var spanmove = document.getElementsByTagName('span');  //获取所有span
    var submit = document.getElementById('btn');           //获取点击按钮

    for (let i = 0; i < spanmove.length; i++) {
      spanmove[i].onmousemove = move                       
      //遍历所有的span,在span上添加移入事件,移入就调用move函数
    }
    submit.onclick = btnClick;
    //添加点击事件,点击调用btnClick

    var index;   //定义一个移入的下标变量

    function move() {  //定义移入函数
      //遍历所有span标签,判断是不是同个span
      for (var i = 0; i < spanmove.length; i++) {
        //这里的spanmove[i]是遍历出来的所有span,this指向了移入事件那里的spanmove[i]
        if (spanmove[i] == this) {
          index = i;    // 两个span下标要是一致的话就把当前下标传给index
        }
      }

      for (let j = 0; j <= index; j++) {
          spanmove[j].classList.remove('off')
          spanmove[j].classList.add('on')
      }
      //遍历 拿到index之后的元素把on类名移除加上off类名
      for (let k = index + 1; k < spanmove.length; k++) {
        spanmove[k].classList.remove('on')
        spanmove[k].classList.add('off')
      }

    }

    //点击输出评价的分数
    function btnClick() {
      alert(`满分5分,您打了${index + 1}分!`)
    }

  </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_48329823/article/details/122412669