2016-02-27 3 views
2

Мне нужно изменить цвет фона div каждые 3 секунды, так как ниже я попытался изменить значение массива color каждые 3 секунды .eg color индекс 0 из «красного» переместится в индекс 1, затем значение индекса 1 переместится в индекс 2 ... Поэтому я устанавливаю последний индекс 4, чтобы всегда индексировать значение 0. Проблема в том, что я не получил этот новый массив редактирования. Как изменить значение массива color в каждый раз вызываемый.Нужно менять фон div каждые 3 секунды?

<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> 
+0

проверить мой ответ и дайте мне знать, если это помогает. –

ответ

1

Мое решение неуклюжим, но это работает, и я сделал это легко следовать (я думаю). Это прокомментировано шаг за шагом.

OP: может также объяснить, почему использование цикла for в процессе получает дополнительную ценность?

Ну, я читал, что петли for in должны использоваться для перебора объектов, потому что нет гарантии, что результат будет в правильном порядке. Поэтому, если вы используете for in для итерации по массиву, most likely it'll return in a different order, который в основном делает массив похожим на объект, но менее полезен, поскольку одним из основных преимуществ массива является его упорядоченный индекс.

Когда вы получаете дополнительное значение, это потому, что for in будет интерпретировать массив и не только дать вам его содержимое: 0,1,2,3,4,, но он также перечислит свойства: length,item,callItem. Я не знаю никаких обстоятельств, когда вам нужно все это. Фактически, div - это только NodeList, если бы он был массивом, у вас был бы больший список свойств.

Plunker

Отрывок

<!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>

0

Заявление о-в само по себе не является «плохой практикой», однако это может быть неправильно использованы, например, для перебора массивов или массивов как объекты.

Цель оператора for-in - перечислить свойства объекта. Это утверждение будет расти в цепочке прототипов, также перечисляя над унаследованными свойствами, что иногда не желательно.

исх: https://stackoverflow.com/a/4261096/2815301

Его хорошо использовать for index.

0

Если я правильно понял, вам нужно изменить цвет всех div из данного массива.

После может работать

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); 
0

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>

+0

Я думаю, что это лучшее решение - нет процедурного кода, поэтому очень легко изменить тайминги; добавлять, удалять или изменять цвета. –

2

Это полезно быть муз.

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>

И Working Jsfiddle

+1

Спасибо за ваш ответ –

0

Вам не нужно немного JavaScript для этой функции:

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>

Если вы используете препроцессор как Sass, вы можете сделать это немного более программный:

$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)}; 
    } 
}