【问题标题】:Javascript/JQuery looping the body background color continuouslyJavascript/JQuery 连续循环正文背景颜色
【发布时间】:2014-02-23 12:18:04
【问题描述】:

我在尝试让 JQuery 和 Javascript 在 for 循环中遍历一组颜色时遇到很多麻烦,将正文的背景颜色设置为每个颜色,然后重新启动该过程。我不知道这是否是最好的方法,但我希望背景颜色切换得非常快。这就是我到目前为止所拥有的。我试图让它由按钮上的 JQuery 事件触发。

$("#button6").click(function() {
    $('#disclaimer').hide();
    $('#button6').hide();
    var colors = Array("red", "green", "blue", "purple" "yellow", "orange);

    var count = 0;
    while ( count < 1000 ) {
    for(var i = 0; i < colors.length; i++) {
        $('body').css("background-color", colors[i]);
        $('body').delay(50);
    }
    count++;
    }
});

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    看看下面的 sn-p。

     var c = ["#81d8d0", "#ffea64", "#89bc84", "#e5cb47", "#9d549c"];
     var i = 0;
     var myVar = setInterval(function () { myTimer() }, 1500);
    
     function myTimer() {
        document.getElementsByTagName('body')[0].style.background = c[i];
        i = i + 1;
        if (i >= c.length) i = 0;
     }
    

    http://jsfiddle.net/bhaumikmehta/8og7v8ad/6/

    【讨论】:

      【解决方案2】:

      为什么不使用 svg + css?

      Animate svg path fill using css

      这是我的代码:

            @keyframes fill {
                0% {
                    fill: red;
                }
                20% {
                    fill: green;
                }
                40% {
                    fill: blue;
                }
                60% {
                    fill: purple;
                }
                80% {
                    fill: yellow;
                }
                100% {
                    fill: orange;
                }
            }
      
            #fill {
                fill: black;
                animation-name: fill;
                animation-duration: 50ms;
                animation-iteration-count: infinite;
            }
          ]]>
      </style>
      <rect id="fill" x="0" y="0" width="60" height="60"/>
      

      您可以将其复制到名为 something.svg 的文件中,并将其用作带有 css 的图像。

      @edit:不知何故,代码在 stackoverflow 上崩溃了,但你可以在这里下载我的示例:https://dl.dropboxusercontent.com/u/49774783/crazy.svg

      【讨论】:

        【解决方案3】:

        .delay() 与动画一起使用,它不会延迟任何东西。我认为setTimeout 在这里更适合你:

        http://jsfiddle.net/thA9q/

        var colors = ["red", "green", "blue", "purple", "yellow", "orange"];
        
        var currentColor = 0;
        function switchColor() {    
            if (currentColor >= colors.length) currentColor = 0;
        
            $('body').css('background-color', colors[currentColor++]);
        
            setTimeout(switchColor, 50);
        }
        
        switchColor();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-09-08
          • 2016-11-18
          • 2016-05-24
          • 2012-12-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多