2014-06-05 52 views
-1

我是一個完整的jquery newb,我想用定時器創建5個類(.button1 - .button5),該定時器切換下一個類:懸停或:連續每4000ms激活狀態循環。我還希望定時器能夠暫停並繼續,如果其他類中的其中一個被用戶佔用。有沒有人知道有一個好的起點或有類似解決方案的線程? 我附上了一張圖。用jQuery定時器更改div的懸停狀態

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> 

回答

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

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

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