2016-04-15 11 views
1

我想讓div #prueba中的css屬性「color」在值「blue」和「green」之間每隔0.5秒更改一次並將此值添加到現有的div #value,但我不知道該怎麼做,我也希望它可以在任何瀏覽器中運行。定期更改css屬性,並將該值作爲文本添加到div中

body { 
 
    text-align: center; 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
#prueba { 
 
    color: red; 
 
    background: grey; 
 
    display: inline; 
 
}
<div id="#value"></div> 
 
<div id="prueba"> 
 
    ABCDE 
 
</div>

+0

從ID刪除 '#' 標誌,因爲它可能會造成混亂 – rubentd

回答

2

setInterval(changeColor, 500) 
 

 
function changeColor() { 
 
    var prueba = document.getElementById('prueba'); 
 
    if (prueba.style.color === 'blue') { 
 
    prueba.style.color = 'green'; 
 
    } else { 
 
    prueba.style.color = 'blue'; 
 
    } 
 
    document.getElementById('value').innerHTML = prueba.style.color; 
 
}
body { 
 
    text-align: center; 
 
    margin: 0; 
 
    padding: 0; 
 
} 
 
#prueba { 
 
    color: red; 
 
    background: grey; 
 
    display: inline; 
 
}
<div id="value">&nbsp;</div> 
 
<div id="prueba"> 
 
    ABCDE 
 
</div>

使用 '的setInterval' 功能

0

您可以使用setInterval()

setInterval(function(){ 
 
    var color = document.getElementById('prueba').style.color; // get current color 
 
    var nextcolor = color === "green" ? "blue" : "green";  // decide what color should be next 
 
    document.getElementById('prueba').style.color = nextcolor ; // apply to div 
 
    
 
    document.getElementById('value').innerHTML = nextcolor +'<br />'; // display the color in 'value' div 
 
}, 500); //500 milliseconds == 0.5 seconds
body{text-align:center; margin:0; padding:0;} 
 
#prueba{ 
 
\t color:red; 
 
\t background:grey; 
 
\t display:inline; 
 
\t }
<div id="value"> 
 
</div> 
 
<div id="prueba"> 
 
ABCDE 
 
</div>