反复改变图片onMouseOver的背景颜色

Kon*_*ras 5 html javascript css nested

我有一张照片,希望它的背景能够改变并重复从整个光谱中顺序拍摄随机颜色,直到用户的鼠标退出图片.我想解决方案应该使用setInterval(请参阅此内容),以下内容将有所帮助:

var red = Math.round(Math.random() * 255);
var green = Math.round(Math.random() * 255);
var blue = Math.round(Math.random() * 255);
var bg = "background-color: rgb(" + red + "," + green + "," + blue + ");";
x.style = bg;
Run Code Online (Sandbox Code Playgroud)

这是一个小提琴试图实现我的想法:第一个笑脸应该改变颜色onMouseOver并返回正常onMouseOut.

以下是我的想法:我想在他们的页脚上实现FontAwesome.com对他们的徽标所做的事情:它会改变颜色,然后停止.但那不是图片,而是字体(?).相反,我有一个透明的徽标,我想动态更改背景,以便复制Fontawesome的精彩技巧.有任何想法吗?

*更新*

我根据社区的答案在下面发布了我的问题的详细解决方案.看起来我跟着Leo的方式,但Rakibul的解决方案也运作良好.

Rak*_*lam 0

您必须声明setInterval()所需的时间间隔(在下面的示例中设置为 500),以便颜色按一定的时间间隔随机更改。用于onmouseover简单地检测图像上的悬停,然后随机设置颜色。最后,当onmouseout检测到时,颜色变为无色。

var randomColor = function() {
  var r = Math.floor(Math.random() * 12);
  var g = Math.floor(Math.random() * 128);
  var b = Math.floor(Math.random() * 100);
  return "#" + r + g + b;
};

var colorChange;

document.getElementById("myImage").onmouseover = function() {
  colorChange = setInterval(function() {
    document.getElementById("myImage").style.backgroundColor = randomColor();
  }, 500);
};

document.getElementById("myImage").onmouseout = function() {
  this.style.backgroundColor = "";
  clearInterval(colorChange);
};
Run Code Online (Sandbox Code Playgroud)
<img id="myImage" src="https://www.w3schools.com/jsref/smiley.gif" alt="Smiley">
Run Code Online (Sandbox Code Playgroud)