2017-10-19 101 views
-1

我有一個問題,有一個元素變成白色,再次點擊紅色。我使用鉻。另外,我不明白我是怎麼做到這一點的,所以我希望得到詳細的答覆。使元素白色一次點擊,並再次點擊紅色

<html> 
 
    <head> 
 
    <script> 
 
     var color = document.querySelectorAll('h1') 
 
     color.onclick = function(){ 
 
      if (this.style.backgroundColor == 'red') { 
 
      this.style.backgroundColor = 'white' 
 
      this.style.color = 'white' 
 
      } 
 
      if (this.style.backgroundColor == 'blue') { 
 
      this.style.backgroundColor = 'white' 
 
      this.style.color = 'white' 
 
      } 
 
      if (this.style.backgroundColor == 'white') { 
 
      this.style.backgroundColor = 'red' 
 
      this.style.color = 'red' 
 
      } 
 

 
     } 
 
    </script> 
 

 
    </body> 
 
</html>

(編輯),我很抱歉,我沒有添加一個片段,而我加入這一個與編輯。我希望有更詳細的解釋,謝謝。 (編輯)

+2

歡迎來到StackOverflow!爲了讓我們更好地爲您提供幫助,能否請您更新您的問題,以便在[**最小,完整和可驗證的示例**]中顯示**相關代碼**(http://stackoverflow.com/幫助/ MCVE)。如果你能讓我們知道你有什麼[**嘗試到目前爲止**](http://meta.stackoverflow.com/questions/261592)來解決你的問題,這也會很有幫助。有關詳細信息,請參閱有關[**如何提出良好問題**](http://stackoverflow.com/help/how-to-ask)的幫助文章,並參加該網站的[**遊覽**](http://stackoverflow.com/tour)) –

回答

0

在沒有一些示例代碼的情況下,確定你想要做什麼確實有點困難,但是如果我試圖在Google上搜索並搜索這個問題,瞭解你想要做的是正確的,你試圖在點擊時替換背景顏色。

首先,您要選擇頁面上的元素。然後應用點擊處理程序。在此點擊處理程序的內部,您需要檢查條件中的背景色,並使用style property。如果顏色是紅色,則將其設置爲白色。如果顏色不是紅色,則將其設置爲紅色。

這可以看出,在下面的例子:

var example = document.getElementById('example'); 
 
example.onclick = function() { 
 
    if (this.style.backgroundColor == 'red') { 
 
    this.style.backgroundColor = 'white' 
 
    } 
 
    else { 
 
    this.style.backgroundColor = 'red' 
 
    } 
 
}
<div id="example">Text</div>

希望這有助於! :)

+0

有沒有辦法對所有元素做到這一點? –

+0

是的。使用['.querySelectorAll()'](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll)。 –

+0

而不是什麼? –

相關問題