Trying to loop between CSS classes/hover states - Jquery

心不动则不痛 提交于 2019-12-12 02:31:53

问题


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:


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


来源:https://stackoverflow.com/questions/10964257/trying-to-loop-between-css-classes-hover-states-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!