更改文本的颜色在HTML

问题描述:

每3秒我得到这个代码,但任何人都可以解释我是如何工作更改文本的颜色在HTML

var text = document.getElementById('film'); 
text.style.color = (text.style.color == 'red') ? 'White' : 'red'; 
+0

['document.getElementById'](https://developer.mozilla.org/en-US/docs/DOM/document.getElementById),['element.style'](HTTPS://显影剂.mozilla.org/en-US/docs/DOM/element.style),[Conditional Operator](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator)... – VisioN 2013-05-10 12:15:25

+4

它使用[ternary运算符](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Conditional_Operator)在颜色之间切换。 – jbabey 2013-05-10 12:15:33

+0

可能的重复[在这个函数中问号是什么意思?](http://*.com/questions/7023317/what-does-the-question-mark-mean-in-this-function) – Quentin 2013-05-10 12:16:41

它是If-else循环的替代方案。这也可以看出来。

if(text.style.color == 'red') 
     text.style.color = 'White'; 
    else 
     text.style.color = 'red'; 

它通过它的ID找到一个HTML元素,那么如果它的风格的颜色属性属性为红色,则切换为白色;否则会变红。相当自我解释,如果你不明白,我建议你寻找更多有关Javascript的学习材料。

如果您希望每三秒更改一次,请使用setInterval函数。

第一行获取具有给定ID的元素的DOM节点(在这种情况下为film)。 第二行从该节点获取style对象,并将color属性设置为redwhite,具体取决于当前值。