在javascript函数中使用jquery animate

时间:2016-05-02 02:58:42

标签: javascript jquery html css animation

我只有一个div background color 覆盖整个视图,名为“ colorPanel ”(使用html id)。

此代码无法运行,我不明白为什么。

当我将col更改为$col时,它仍然无法运行。

我对jquery不了解什么?

function animateColors(i){
    var val = 1/0.2*(i) * 210;
    var col = 'hsla('+val+', 90%, 60%, 1)';
    $("#colorPanel").animate({"background-color": col}, 200);
    i = (i<180)? i+4 : 0;
    animateColors(i);
}

animateColors();

1 个答案:

答案 0 :(得分:2)

  

已经@brut&amp; @tiantang建议将有效点作为评论。请考虑一下。

     

你没有将任何内容传递给animateColors()的初始调用。这是一个打字机吗?如果不是我没有为程序的初始运行定义。此外,您的递归函数没有终止条件。

     

documentation,&#34; .animate()方法允许我们在任何数字CSS属性上创建动画效果。&#34;和&#34;例如,宽度,高度或左边可以设置动画,但背景颜色不能,除非使用jQuery.Color插件&#34;。根据您的要求,您可以使用CSS转换。

根据这些评论,我将对您的代码进行更改。

&#13;
&#13;
$(document).ready(function(){
    function animateColors(i){
        var val = 1/0.2*(i) * 210;
        var col = 'hsla('+val+', 90%, 60%, 1)';
        $("#colorPanel").css({"background-color": col});
        i = (i<180)? i+4 : 0;
        // animateColors(i); // when using this too much recursion error occur
        setTimeout( function(){animateColors(i)}, 500);
    }
    animateColors(1);
});
&#13;
#colorPanel {
  height: 20px; /*your wish*/
  width: 100%; /*your wish*/
  transition: all ease 0.5s; /*for animation effect*/
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="colorPanel"></div>
&#13;
&#13;
&#13;

我希望这会对你有所帮助。