【问题标题】:jQuery Rapid Class SwitcherjQuery 快速类切换器
【发布时间】:2011-11-30 04:26:48
【问题描述】:

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

尝试制作一个将执行以下操作的类切换器:

  1. 加载时 - 随机选择 10 个类中的一个添加到元素中
  2. 悬停时 - 在 10 个类之间快速(每 0.4 秒)切换
  3. 在 mouseOut 上 - 使当前类保持活动状态

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

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

【问题讨论】:

  • @FishBasketGordo 别担心它已经解决了

标签: jquery class hover switch-statement


【解决方案1】:

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);

【讨论】:

  • 哇,我没想到有人会为我做这一切,谢谢!!
【解决方案2】:

这里有一个在你的 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;
});

【讨论】:

  • 有什么办法可以把它打包成像.switchclasses()这样的jquery函数
  • @JamesKyle - 在您的 jsFiddle 实现中,您必须在另一个您错过的地方将“类”更改为“状态”:jsfiddle.net/jfriend00/nPVxb/80。
  • 不需要包装。在代码中,将".element" 更改为".switcher",然后将"switcher" 添加到您想要具有此行为的任何元素。如果 switcher 类位于原始页面 HTML 中的对象上,则此代码将仅适用于具有该类的任何对象。如果您想动态添加switcher 类,则必须根据您使用的jQuery 版本更改代码以使用.live() 或.on()。
  • 谢谢!!!你可以在这里看到它的使用:playground.thejameskyle.com/qwiqly/index.html
猜你喜欢
  • 2011-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-28
  • 2011-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多