使用jQuery计时器更改div的悬停状态

时间:2014-06-05 13:44:30

标签: javascript jquery html css timer

我是一个完整的jquery newb,我想用一个定时器来创建5个类(.button1 - .button5),它可以切换下一个类:hover或:连续循环中每4000ms的活动状态。我还希望计时器能够暂停并继续,如果用户徘徊了另一个类。有没有人知道一个好的起点或一个类似解决方案的线程? 我附上了一张图表。

enter image description here

CSS

.wrapper { width:100%; margin:0 auto; background:#f3f3f3; }
#buttonblock { display:block; }
.button1, .button2, .button3, .button4, .button5 { display:inline-block; margin:0 5px; height:50px; width:50px; border-radius:25px; background:#3cc8dd; }
.button1:hover, .button2:hover, .button3:hover, .button4:hover, .button5:hover{ background:#fbc040; }

HTML

<div class="wrapper">
<div id="buttonblock">
    <div class="button1"></div>
    <div class="button2"></div>
    <div class="button3"></div>
    <div class="button4"></div>
    <div class="button5"></div>
</div>
</div>

3 个答案:

答案 0 :(得分:1)

你可以简单地遍历对象数组,例如

var $block = $('#buttonblock div');

for (var n=0; n<$block.length; n++)
{
    var domELM = $block[n]; // you can do $(domELM) to create a jquery of the dom
    // do stuff here, set interval or whatever it is you wish to do.
    if(n == $block.elngth)
    n=0; //resets the loop
}

答案 1 :(得分:1)

HTML

<div class="wrapper">
<div id="buttonblock">
    <div class="button button1"></div>
    <div class="button button2"></div>
    <div class="button button3"></div>
    <div class="button button4"></div>
    <div class="button button5"></div>
</div>

CSS

.hover {
 background:#fbc040;
}

JS

var counter = 1;
var timer;
$(document).ready(function () {
 startTimer();
 $('.button').mouseenter(function () {
    $('.hover').removeClass('hover');
    clearInterval(timer);
 });

 $('.button').mouseleave(function () {
    startTimer();
 });
});

function startTimer() {
 timer = setInterval(function () {
  counter = (counter > 5) ? 1 : counter;
  $('.hover').removeClass('hover');
  $('.button' + counter).addClass('hover');
  counter++;
 }, 4000);
}

JSFiddle

答案 2 :(得分:0)

试试这个

var divs = $('#buttonblock').children('div'),
    number = divs.length,
    currentIndex = 0,
    intervalLength = 2000;

function setTimer() {
    divs.removeClass('hover');
    divs.eq(currentIndex).addClass('hover');
    currentIndex++;
    if (currentIndex == number) {
        currentIndex = 0;
    }
}

setTimer();
var timer = setInterval(setTimer, intervalLength);

divs.mouseenter(function () {
    clearInterval(timer);
    divs.removeClass('hover');
    var div = $(this);
    div.addClass('hover');
    currentIndex = divs.index(div);
}).mouseleave(function () {
    timer = setInterval(setTimer, intervalLength);
});

Example - setInterval

or using setTimeout