2011-11-30 84 views
0

http://jsfiddle.net/JamesKyle/re73T/jQuery的快速類切換

試圖使一個類切換器,將執行以下操作:

  1. 在負載 - 隨機選擇10類中的一個添加到一個元件
  2. 懸停時 - 快速(每0.4s)切換10級
  3. On mouseOut - lea已經在當前類活性

我試着這樣做的幾種方法,其中沒有工作過。

您認爲最好的方法是做什麼?

+0

@FishBasketGordo不用擔心它解決了 –

回答

1

這裏有不同的實現,在你的jsfiddle這裏工作:http://jsfiddle.net/jfriend00/b7A4a/。這也確保了隨機生成的類名與前一個類不同,所以顏色實際上每400ms更改一次,而不是跳過10次中的1次,因爲它會生成與剛纔相同的顏色值。

// get unique random class that's different than what is currently being used 
function getRandomClass(prior) { 
    var r; 
    do { 
     r = "class" + (Math.floor(Math.random() * 10) + 1); 
    } while (prior && prior.match(new RegExp("\\b" + r + "\\b"))); 
    return(r); 
} 

// initialize the current class 
$(".element").addClass(getRandomClass()); 

// upon hover, start the timer, when leaving stop the timer 
$(".element").hover(function() { 
    var self = this; 
    if (this.intervalTimer) { 
     clearInterval(this.intervalTimer); 
     this.intervalTimer = null; 
    } 
    this.intervalTimer = setInterval(function() { 
     var c = self.className; 
     self.className = c.replace(/\bclass\d+\b/, getRandomClass(c)); 
    }, 400); 
}, function() { 
    clearInterval(this.intervalTimer); 
    this.intervalTimer = null; 
}); 
+0

http://jsfiddle.net/JamesKyle/nPVxb/78/ –

+0

爲什麼它不在這裏工作?我錯過了什麼 –

+0

有沒有什麼辦法可以打包成jquery函數,如'.switchclasses()' –

2

http://jsfiddle.net/re73T/9/

// On Load 
//  Randomly select 1 of 10 classes 


function removeAllClasses() { 
    var i; 
    for (i = 0; i <= 10; i += 1) { 
     $('.element').removeClass('class' + i); 
    } 
} 

function setRandomClass() { 
    var cls = "class"+Math.floor(Math.random() * (10 - 1 + 1) + 1); 
    $('.element').addClass(cls); 
} 

$(document).ready(function() { 
    removeAllClasses(); // just in case 
    setRandomClass(); 
}); 

// While Hovering 
// every 0.4s 
//  switch to the next class out of ten 
// I want it to leave the current class when you mouseout 
var IS_HOVERING = false; 
$('.element').hover(function() { 
    IS_HOVERING = true; 
}, function() { 
    IS_HOVERING = false; 
}); 

function onTimeout() { 
    if (IS_HOVERING) { 
     removeAllClasses(); 
     setRandomClass(); 
    } 
    setTimeout(onTimeout, 400); 
} 

setTimeout(onTimeout, 400); 
+0

哇我沒想到有人真正做到一切爲我,謝謝! –