Trying to loop between CSS classes/hover states -

2019-08-22 16:16发布

I am trying to create a function in JQuery which animates a couple links between their non-hovered and hover states indefinitely until my abortTimer function is fired. I would like to animate between a.mus-plr and a.earbuds at opposing times, so when one of the elements has it's '.hover' class enabled, the other would not have it's '.hover' class enabled. I would like each element to switch between it's hover states every 3000 milliseconds.

Any help would be much appreciated! I can't seem to get this to work. I'm thinking it might be a problem with how I've defined my setInterval timer. Thanks!!

JQuery file:

$(document).ready(function(){
    var tid = setInterval(animateControls, 4000);
    function animateControls() {
        $("a.mus-plr").delay(2000).addClass('hover').delay(2000).removeClass('hover');
        $("a.earbuds").addClass('hover').delay(2000).removeClass('hover');
    }
    function abortTimer() {
        clearInterval(tid);
    }
});

1条回答
Explosion°爆炸
2楼-- · 2019-08-22 16:50

You simply toggle the hover class each time your interval timer expires, assuming they start off with one having and the other not having the hover class.

Edited to stop the automated toggle when an element is hovered.

$(function() {
     var doToggle = true;

     $('a.mus-plr').removeClass('hover');
     $('a.earbuds').addClass('hover');

     var tid = setInterval( function() {
          if (doToggle) $('a.mus-plr, a.earbuds').toggleClass('hover');
     }, 2000);

     setTimeout(function() {
        if (tid) clearInterval(tid);
        $('a.mus-plr,a.earbuds').removeClass('hover');
     }, 30000); // stop toggling after 30 seconds

     $('a.mus-plr,a.earbuds').hover( function() {
           doToggle = false;
     }, function() {
           doToggle = true;
     });
});
查看更多
登录 后发表回答