2017-08-10 47 views
-1

我想鏈接顏色以便在連續懸停時進行更改,但它永遠不會按照我希望的方式工作 - 它不會停在mouseleave /懸停在外,您可以看到,在此fiddleclearInterval無法在mouseleave上工作

var interv; 

    function changeColors(item) { 
    interv = setInterval(function() { 
     $(item).animate({ 
      color: 'red' 
     }, 1000) 
     .animate({ 
      color: 'green' 
     }, 1000); 
    }, 100); 
    }; 

    $(document).ready(function() { 

    $('a') 
     .mouseenter(function() { 
     changeColors(this); 
     }) 
     .mouseleave(function() { 
     clearInterval(interv); 
     $(this).removeAttr("style"); 
     }); 


    }); 

然後我試圖重新這是什麼comment建議,但你可以在這個fiddle看到,它不工作之一:

$(document).ready(function() { 
    var interval; 
    $('a').hover(
    function() { 
     if (interval) 
     clearInterval(interval); 
     interval = setInterval(function() { 
     $('a').animate({ 
      color: 'red' 
      }, 1000) 
      .animate({ 
      color: 'green' 
      }, 1000); 
     }, 10); 
    }, 
    function() { 
     clearInterval(interval); 
     interval = null; 
     $(this).removeAttr("style"); 
    } 
); 
}); 
+0

uhm ...你的間隔是0 ...它不起作用,因爲你在鼠標懸停的時候排隊了數以千計的動畫。它會一直持續到你完成了所有開始的動畫。間隔是這裏工作的錯誤工具。 –

+0

哎呀,使用jquery進行動畫也可能是錯誤的工具。你可以單獨使用CSS獲得相同的效果,並使用類將其打開/關閉。 [這是一個問題,問如何用CSS單獨做動畫](https://stackoverflow.com/questions/16782498/looping-animation-of-text-color-change-using-css3),結合一個類應該放輕鬆。 –

回答

0

在你的CSS,你將需要設置轉換,這些交易和你的動畫:

a { 
    transition: all 1000ms ease-in-out; 
    -webkit-transition: all 1000ms ease-in-out; 
} 

在JS文件,您只需設置通過jQuery的CSS,而不是依賴於.animate(),這使您可以通過CSS來控制簡單的動畫:

var int; 

function changeColors(item, currentColor) { 
    int = setInterval(function() { 

     $(item).css({ 
      color: currentColor 
     }, 1000) 

     if (currentColor == 'red') { 
      currentColor = 'green'; 
     } else { 
      currentColor = 'red'; 
     } 

    }, 1000); 
}; 

$(document).ready(function() { 

    $('a').mouseenter(function() { 

     changeColors(this, 'red'); 

    }); 

    $('a').on('mouseleave', function() { 

     $(this).removeAttr('style'); 
     clearInterval(int); 

    }); 
}); 

對於那些誰正在尋找與隨機顏色類似的東西:

Random color generator