Continuously add and remove class to a random elem

2019-08-23 09:02发布

Let's say I have an unordered list of ten elements.
I'd like a class to be added to one of them at random, and then remove that class after a couple of seconds and start again with another randomly chosen element indefinitely.

What would be the cleanest way to achieve that?

edit: What I've got so far:

<ul id="hideAndSeek">
  <li>...</li>
  <li>...</li>
  <li>...</li>
  <li>...</li>
  ...
</ul>

And the jQuery:

var random = Math.floor(Math.random() * 1000);

var shownElement = $("#hideAndSeek li");
shownElement.eq(random % shownElement.length).addClass("shown");

However, this obviously does not run continuously, and I don't know how to properly set a delay before removing the class.

2条回答
狗以群分
2楼-- · 2019-08-23 09:32

You need to use setInterval to create a timer, and then you can choose a random number and set the class for that item index.

Something like this:

HTML

<ul>
    <li>one</li>
    <li>two</li>
    <li>three</li>
    <li>four</li>
    <li>five</li>
    <li>six</li>
    <li>seven</li>
    <li>eight</li>
    <li>nine</li>
    <li>ten</li>
</ul>

Javascript (w/ JQuery)

setRandomClass();
setInterval(function () {
    setRandomClass();
}, 2000);//number of milliseconds (2000 = 2 seconds)

function setRandomClass() {
    var ul = $("ul");
    var items = ul.find("li");
    var number = items.length;
    var random = Math.floor((Math.random() * number));
    items.removeClass("special");
    items.eq(random).addClass("special");
}

Here is a working example

查看更多
萌系小妹纸
3楼-- · 2019-08-23 09:51

Could do something like this:

HTML

<ul id="randomCol">
    <li>test1</li>
    <li>test2</li>
    <li>test3</li>
    <li>test4</li>
    <li class="color">test5</li>
    <li>test6</li>
    <li>test7</li>
    <li>test8</li>
    <li>test9</li>
    <li>test10</li>
</ul>

Jquery

var tid = setInterval(changeUp, 1000);
function changeUp() {
  var i = Math.floor((Math.random()*9));
  $('#randomCol').children().removeClass('color');
   $('#randomCol').children().eq(i).addClass('color');
}

fiddle

查看更多
登录 后发表回答