jQuery的快速类切换

问题描述:

http://jsfiddle.net/JamesKyle/re73T/jQuery的快速类切换

试图使一个类切换器,将执行以下操作:

  1. 在负载 - 随机选择10类中的一个添加到一个元件
  2. 悬停时 - 快速(每0.4s)切换10级
  3. On mouseOut - lea已经在当前类活性

我试着这样做的几种方法,其中没有工作过。

您认为最好的方法是做什么?

+0

@FishBasketGordo不用担心它解决了 –

这里有不同的实现,在你的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()' –

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

哇我没想到有人真正做到一切为我,谢谢! –