Rating stars for native JavaScript

Ideas:

        1. Arrange five stars, the first one is solid by default, and the others are hollow.

        2. When the mouse moves into a star, judge the subscript of the current star, and the moved star, including the previous star, becomes solid

        3. When the submit button is clicked, the score of the review pops up

        4. I downloaded the icon from the Ali icon library

When the mouse moves into the star, it will become solid:

Clicking will output the score:

Here is the complete code:

<!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>

Guess you like

Origin blog.csdn.net/weixin_48329823/article/details/122412669