2013-05-10 70 views
0

每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://stackoverflow.com/questions/7023317/what-does-the-question-mark-mean-in-this-function) – Quentin 2013-05-10 12:16:41

回答

1

它是If-else循環的替代方案。這也可以看出來。

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

它通過它的ID找到一個HTML元素,那麼如果它的風格的顏色屬性屬性爲紅色,則切換爲白色;否則會變紅。相當自我解釋,如果你不明白,我建議你尋找更多有關Javascript的學習材料。

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

1

第一行獲取具有給定ID的元素的DOM節點(在這種情況下爲film)。 第二行從該節點獲取style對象,並將color屬性設置爲redwhite,具體取決於當前值。