尝试根据当前背景更改背景颜色:背景颜色没有值

attempting to change background color based on current background: background color has no value

本文关键字:背景 颜色      更新时间:2023-09-26

这是一个非常简单的应用程序。基本上,我用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();

document.body.style。backgroundColor不读取css文件中设置的颜色,只读取元素上的style属性设置的颜色。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>