为什么javascript无法获得样式值但可以更改它?

时间:2014-11-27 16:27:07

标签: javascript dom

我需要将标签数据传递给函数并在该函数中读取它, 我试图通过"这个"传递标签。 ,我可以改变一些风格元素,但我无法读取那里的风格数据。有什么问题

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS</title>
<script>
function paint(tab){
    window.alert(tab.style.backgroundColor); // It can't show current color
    tab.style.backgroundColor="#000000";
}
</script>
<style>
div.vtab {
  background-color:#ff0000;
  height: 80px;
  left: 20px;
  position: absolute;
  width: 80px;
  cursor:pointer;
}
</style>

</head>

<body>
<div onclick="javascript:paint(this)" class="vtab" ></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

元素上的style对象只将样式信息专门应用于元素,而不是通过样式表应用于它的信息。首先,您的tab.style.backgroundColor将为空,因为元素上没有style="background-color: ..."

要获取元素的计算样式,可以使用getComputedStyle函数(在任何现代函数上)或currentStyle属性(在旧IE上):

alert(getComputedStyle(tab).backgroundColor);

对于旧的IE,很容易添加一个简单的垫片:

if (!window.getComputedStyle) {
    window.getComputedStyle = function(element, pseudo) {
        if (typeof pseudo !== "undefined") {
            throw "The second argument to getComputedStyle can't be polyfilled";
        }
        return element.currentStyle;
    };
}

示例:

if (!window.getComputedStyle) {
  window.getComputedStyle = function(element, pseudo) {
    if (typeof pseudo !== "undefined") {
      throw "The second argument to getComputedStyle can't be polyfilled";
    }
    return element.currentStyle;
  };
}
var div = document.querySelector(".foo");
snippet.log("Background color before changing: " +
            getComputedStyle(div).backgroundColor);
setTimeout(function() {
  div.style.backgroundColor = '#4ff';
  snippet.log("Background color after changing: " +
              getComputedStyle(div).backgroundColor);
}, 1000);
.foo {
  background-color: #ff4;
}
<div class="foo">My background is yellow to start with, because of the class <code>foo</code>, then code turns it cyan</div>

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>