2016-04-15 8 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>