简体   繁体   中英

Need to change div background every 3 seconds?

I have to change div background color in every 3 seconds ,so as below I tried to change color array value in every 3 seconds .eg color index 0 of "red" will move to index 1,then index 1 value move to index 2...So I set last index 4 to always index 0 of value.The problem is that I didn't get that new edit array.How to edit color array value in every times called.

<style type="text/css">
 div {
    width: 100%;
    height: 20%;
    position: relative;
    background: #fff;
     }
</style>
<body>
 <div></div>
 <div></div>
 <div></div>
 <div></div>
 <div></div>

 <script>
       var div = document.getElementsByTagName("div");
       var color = ["red","green","pink","blue","lightblue"];
       function change(){
          for(var i in color){
             var j = parseInt(i);
             j !== 4 ? color[j+1].Key = color[j] : color[0].Key = color[j];
          }
       changediv();
      }
      function changediv () {
        for(var d = 0 ; d < div.length; d ++){
                 div[d].style.background = color[d];
            }
        //can u also explain why using for in loop is getting additional value .see console.log output
        //for(var i in div){
        //         div[i].style.background = color[i];
        //  console.log(i); // 0,1,2,3,4,length,item,callItem   
        //    }
      }

     setInterval(change,3000);
</script>

This mus be helpful.

 var divs = document.getElementsByTagName("div"); var color = ["red","green","pink","blue","lightblue"]; var colorIndex = 0; var divIndex = 0; function change (){ for(var i = 0 ; i < divs.length; i ++){ divs[divIndex].style.background = color[colorIndex]; colorIndex++; colorIndex = (colorIndex == color.length?0:colorIndex); divIndex++; divIndex = (divIndex == divs.length?0:divIndex); } divIndex++; divIndex = (divIndex == divs.length?0:divIndex); } setInterval(change,1000); 
 div{ height:50px; width:50px; } span { display: flex; } 
  <span> <div></div> <div></div> <div></div> <div></div> <div></div> </span> 

And a Working Jsfiddle

My solution is clunky but it works and I made it easy to follow (I think). It's commented step by step.

OP: can u also explain why using for in loop is getting additional value?

Well I've read that for in loops should be used to iterate through objects because there's no guarantee that the result will be in the correct order. So if you use for in to iterate through an array, most likely it'll return in a different order which basically makes an array like an object but less useful since one of the fundamental strength of an array is it's ordered index.

When you are getting an extra value, it's because for in will interpret an array and not only give you it's contents: 0,1,2,3,4, but it'll enumerate properties as well: length,item,callItem . I don't know any circumstances when you need all of that mucking things up. Actually, div is just a NodeList, if it was an array, you'd have a bigger list of properties.

Plunker

Snippet

 <!DOCTYPE html> <html> <head> <style> div { width: 100%; height: 20vh; border: 1px solid #fff; background: #555; } </style> </head> <body> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> <script> //Declare color Array var color = ["red","green","pink","blue","lightblue"]; //Function takes one argument function fill(color) { //Collect all divs and make a NodeList var divList = document.querySelectorAll('div'); //Make the NodeList an Array var divArray = Array.prototype.slice.call(divList); //Iterate through divArray for(var i = 0; i < divArray.length; i++) { //Each iteration of divArray is matched to an element of color var div = divArray[i]; var bg = color[i]; //Set each background of div to the corresponding color in color Array div.style.backgroundColor = bg; } } setInterval(function() { //Call fill with the given Array color fill(color); //x is the last element of color Array var x = color[4]; //Remove x from the back of color Array color.pop(x); //Place x to the front of color Array color.unshift(x); //Do it again in 3 seconds }, 3000); </script> </body> </html> 

The for-in statement by itself is not a "bad practice", however it can be mis-used, for example, to iterate over arrays or array-like objects.

The purpose of the for-in statement is to enumerate over object properties. This statement will go up in the prototype chain, also enumerating over inherited properties, a thing that sometimes is not desired.

ref: https://stackoverflow.com/a/4261096/2815301

Its good to use for index .

If I understood correctly you need to change color of all div's from the given array.

Following can work

var divs = document.getElementsByTagName("div");
var color = ["red","green","pink","blue","lightblue"];
var index = 0

function change (){
   for(var d = 0 ; d < divs.length; d ++){
                 divs[d].style.background = color[index];
            }
    index++;
    index = index === color.length?0:index;
}

setInterval(change,3000);

 div { width: 100%; height: 20%; position: relative; background: #fff; animation:myfirst 12s; -moz-animation:myfirst 12s infinite; /* Firefox */ -webkit-animation:myfirst 12s infinite; /* Safari and Chrome */ } @-moz-keyframes myfirst /* Firefox */ { 0% {background:red;} 25% {background:green;} 50% {background:pink;} 75% {background:blue;} 100% {background:lightblue;} } @-webkit-keyframes myfirst /* Firefox */ { 0% {background:red;} 25% {background:green;} 50% {background:pink;} 75% {background:blue;} 100% {background:lightblue;} } 
  <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> 

You don't need a bit of JavaScript for this one:

 div { animation: cycle-colors 15s steps(1, end); -moz-animation: cycle-colors 15s steps(1, end) infinite; -webkit-animation: cycle-colors 15s steps(1, end) infinite; } @-moz-keyframes cycle-colors { 0% { background: red; } 20% { background: green; } 40% { background: pink; } 60% { background: blue; } 80% { background: lightblue; } } @-webkit-keyframes cycle-colors { 0% { background: red; } 20% { background: green; } 40% { background: pink; } 60% { background: blue; } 80% { background: lightblue; } } 
 <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> 

If you use a pre-processor like Sass, you can make this a little more programmatic:

$colors: (
  red,
  green,
  pink,
  blue,
  lightblue
);
$colors-length: length($colors);
$frame-duration: 3s;
$animation-duration: $frame-duration * $colors-length;

div {
  animation:cycle-colors $animation-duration steps(1, end);
 -moz-animation:cycle-colors $animation-duration steps(1, end) infinite;
 -webkit-animation:cycle-colors $animation-duration steps(1, end) infinite;
}


@-moz-keyframes cycle-colors {
  @for $i from 1 through $colors-length {
    $stop: 100 / $colors-length * ($i - 1) + 0%;
    #{$stop} { background: nth($colors, $i)};
  }
}

@-webkit-keyframes cycle-colors { 
  @for $i from 1 through $colors-length {
    $stop: 100 / $colors-length * ($i - 1) + 0%;
    #{$stop} { background: nth($colors, $i)};
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM