例如更改div的背景颜色

例如更改div的背景颜色

本文介绍了延迟事件,例如更改div的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将<delay>用于事件的延迟,例如更改背景颜色.我希望事件遵循我想要的延迟时间,但是结果表明我的事件不符合我想要的顺序.我希望第一个在1秒内变成红色.然后第二个在2秒内变成红色.然后第三个在0.8秒内变成红色.而且我不知道如何使它们具有不同的颜色.非常感谢您的帮助.

I am trying to use the <delay> for the delay of the event, such as change the background color. I want the event to follow the delay time I want, but the result shows me that they are not in the order I want. I am expecting the first one become red in 1 second. Then the second one become red in 2 seconds. Then the third one become red in 0.8 seconds. And I don't know how to make them the different color.Thank you very much for the help.

$(document).ready(function(){
    var delayTime = [1000, 2000, 800];
    var bcolor = ['red','blue','green'];
    var i = 0;
    $('#play').click(function(){
        $('div').each(function(){
            $(this).delay(delayTime[i]).queue( function(next){
                $(this).css('background','red');
                next();
            });
            i++;
        }); // end of each
    });
 }); // end ready
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="red" style="width:100px; height: 100px; background-color: white" ></div>
<div id="blue" style="width:100px; height: 100px; background-color: white"></div>
<div id="green" style="width:100px; height: 100px; background-color: white"></div>
<button id="play">Play</button>
<h1 id="test"></h1>

推荐答案

第一:您可以使用index of div

第二个:对于delayTime,您可以在新时间上添加前一个时间以获得正确的延迟时间.因此,如果您有[1000,2000,800],则新的延迟时间将为1000然后是3000然后是3800,依此类推

2nd: for delayTime you can add a previous time to the new one to get the right delay time .. So if you have [1000 , 2000 , 800] the new delay time will be 1000 then 3000 then 3800 and so on

您可以使用此代码

$(document).ready(function(){
    var delayTime = [1000, 2000, 800];
    var bcolor = ['red','blue','green'];
    var timeDelay = 0;
    $('#play').click(function(){
        $('div').each(function(i){  // i mean index of div starts from 0
            timeDelay += delayTime[i]; // add a pervious delayTime (the trick here)
            $(this).delay(timeDelay).queue( function(){
                $(this).css('background', bcolor[i]); //use bcolor[i] to get a color
            });
        }); // end of each
    });
 }); // end ready
<script  src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<div id="red" style="width:100px; height: 100px; background-color: white" ></div>
<div id="blue" style="width:100px; height: 100px; background-color: white"></div>
<div id="green" style="width:100px; height: 100px; background-color: white"></div>
<button id="play">Play</button>
<h1 id="test"></h1>

这篇关于延迟事件,例如更改div的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:01