2015-06-04 155 views
0

因此,這是一個非常簡單的應用程序。基本上,我有我的初始背景由CSS設置。我希望能夠讀取JavaScript中的當前背景顏色並進行更新。目前,我在updateBackground函數中的警報根本沒有顯示任何文本,儘管我的CSS確實已加載,並且由於等待deviceReady而沒有競爭問題。我可以很容易地通過在javascript中設置backgroundColor來解決這個問題,但我想了解這種行爲。嘗試根據當前背景更改背景顏色:背景顏色沒有值

CSS

body{ 
background-color: green; 
} 

的Javascript

var updateBackground = function() { 
     alert(document.body.style.backgroundColor); 
     document.body.style.backgroundColor=document.body.style.backgroundColor == '#E4E4E4' ? 'green' : '#E4E4E4'; 
    }; 
class App{ 
    constructor() { 
     this.bindEvents(); 
    } 
    bindEvents() { 
     document.addEventListener('deviceready', this.onDeviceReady, false); 
    } 
    onDeviceReady(){ 
     document.addEventListener('touchstart', function() { 
      updateBackground(); 
     }, false); 
    } 
} 
var app = new App(); 
+0

你看過什麼顏色報道?瀏覽器不會返回您設置的內容。您最好在元素上切換類。 – epascarello

+0

document.body.style.backgroundColor不會讀取您的css文件中設置的顏色,只有您通過元素上的style屬性設置的顏色。 getComputedStyle(document.body).getPropertyValue(「background-color」)是你想要的。 – Lain

+0

謝謝你,這將是訣竅。 – mrfixij

回答

1

document.body.style.backgroundColor不讀取顏色在你的CSS文件中設置,只有一個你的風格屬性設置元素上。 getComputedStyle(document.body).getPropertyValue(「background-color」)是你想要的。

<html> 
    <head> 
     <style> 
      body{background-color: green} 
     </style> 

     <script> 
      function getStyle(){ 
       alert(getComputedStyle(document.body).getPropertyValue('background-color')) 
      } 
     </script> 
    </head> 

    <body onload = 'getStyle()'> 

    </body> 
</html>