简体   繁体   English

如何<span>以随机间隔更改多个背景颜色?</span>

[英]How can I change multiple <SPAN> 's backgroundColor at random intervals?

So I have multiple spans like this:所以我有多个这样的跨度:

<span unselectable="on" 
    onmouseover="this.style.backgroundColor='#ffcc99';"
    onmouseout="this.style.backgroundColor='#a8c0f0';"
    onclick="javascript stuff" 
    style="-webkit-user-select:none;
        -moz-user-select:none;
        display: inline-block; 
        cursor: pointer;
        font-family: arial; 
        background: #a8c0f0;
        padding-top:9px;
        padding-bottom:9px;
        padding-right:9px;
        padding-left:9px;">
    My Span
</span>

I'd like them to twinkle/blink if you will, with each changing background colors from their normal color state to another color I'll define for just about.5 to 1 second and then back to their normal color.如果你愿意的话,我希望它们闪烁/闪烁,每次将背景 colors 从正常颜色 state 更改为另一种颜色,我将定义大约 5 到 1 秒,然后恢复正常颜色。

But I would like them all to fire at random times so it doesn't look like a pattern.但我希望它们都在随机时间开火,所以它看起来不像一个模式。 Just occasional lazy twinkles.只是偶尔慵懒的闪烁。 Like once every 8-15 seconds.就像每 8-15 秒一次。

I noticed "onload" doesn't work with SPANs so I'm not sure how I would do it.我注意到“onload”不适用于 SPAN,所以我不知道该怎么做。

  • Get a reference to all span elements.获取对所有span元素的引用。
  • Store their original background color with style.backgroundColor .使用style.backgroundColor存储它们的原始背景颜色。
  • Generate a random number of seconds.生成随机秒数。
  • Use setInterval() with a 1000 interval.使用间隔为1000setInterval()
  • Each interval, decrement the random number of seconds.每个间隔,递减随机秒数。 When it is 0, change the background color.当它为 0 时,改变背景颜色。 Use a new setTimeout() to restore the original color.使用新的setTimeout()恢复原始颜色。
  • Generate a new random number of seconds and repeat.生成一个新的随机秒数并重复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM