悬停时生成随机颜色

use*_*123 2 javascript jquery

每次我将鼠标悬停在盒子上时,我都会尝试生成随机颜色。现在,它只会生成一种随机颜色一次。

这是我的 Jquery:https://jsfiddle.net/Mulk/q0hxw0yd/#&togetherjs=uB54KHo5BN

到目前为止,这是我的代码:

$(document).ready(function(){

    var r = Math.floor(Math.random() * (255 - 0) + 0);
    var g = Math.floor(Math.random() * (255 - 0) + 0);
    var b = Math.floor(Math.random() * (255 - 0) + 0);
    var color = "rgb("+r+","+g+","+b+")"

    $("#container").hover(function(){
        $(this).css("background-color", color);
        }, function(){
        $(this).css("background-color", color);
    });

});
Run Code Online (Sandbox Code Playgroud)

hak*_*Jav 5

您只需要将颜色生成放在悬停()函数中,以便它在每个悬停事件上生成新颜色:https ://jsfiddle.net/q0hxw0yd/3/

$(document).ready(function(){
  $("#container").hover(function(){
      var r = Math.floor(Math.random() * 255);
      var g = Math.floor(Math.random() * 255);
      var b = Math.floor(Math.random() * 255);
      var color = "rgb("+r+","+g+","+b+")"
      $(this).css("background-color", color);
  });
});
Run Code Online (Sandbox Code Playgroud)

另外:正如用户评论的那样,(255 - 0) + 0相当于255......不知道为什么在原始代码中!