jQuery Rapid Class Switcher

时间:2011-11-30 04:26:48

标签: jquery class hover switch-statement

  

http://jsfiddle.net/JamesKyle/re73T/

尝试制作能够执行以下操作的班级切换台:

  
      
  1. On Load - 随机选择10个类中的一个添加到元素
  2.   
  3. 徘徊 - 快速(每0.4秒)在10个班级之间切换
  4.   
  5. 在mouseOut上 - 让当前类保持活动状态
  6.   

我尝试了几种方法,但都没有效果。

  

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

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

这里有一个不同的实现,适用于你的jsFiddle:http://jsfiddle.net/jfriend00/b7A4a/。这个也确保随机生成的类名与前一个不同,因此颜色实际上每400毫秒更改一次而不是跳过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;
});