我想在鼠标悬停时交换多个图像,并正在寻找一种方法来做到这一点。我希望“点亮”多颗星星。下面的代码仅适用于一个,但是当光标悬停在第三颗星上时,点亮三颗星的最佳方法是什么?

<div class="rating" data-value="4">
 <img src="star.png"/>
 <img src="star.png"/>
 <img src="star.png"/>
 <img src="star.png"/>
</div>


和JS:

$(".rating > img") .mouseover(function () {
            this.src= "star-on.png";
        }).mouseout(function () {
            this.src= "star.png";

});

最佳答案

您可以通过获取鼠标悬停的集合中恒星的索引,然后根据该索引替换正确数量的恒星来做到这一点:



$(".rating > img").mouseover(function () {
    // Get the index of the star that is being hovered over
    var idx = $("img").index(this);

    // Loop only over the stars that should be highlighted and highlight them.
    // Use the index to know how many to loop over
    for(var i = 0; i < idx + 1; i++){
      // "Light up" the star:
      $(".rating > img")[i].src= "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d8/Full_Star_Blue.svg/2000px-Full_Star_Blue.svg.png";
    }
  }).mouseout(function () {

    // Turn off all stars
    $(".rating > img").each(function(){
    this.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Empty_Star.svg/1024px-Empty_Star.svg.png"
  });

});

img {
 width:30px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="rating" data-value="4">
 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Empty_Star.svg/1024px-Empty_Star.svg.png">
 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Empty_Star.svg/1024px-Empty_Star.svg.png">
 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Empty_Star.svg/1024px-Empty_Star.svg.png">
 <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e7/Empty_Star.svg/1024px-Empty_Star.svg.png">
</div>

09-27 16:45