为什么javascript不能获取样式值,但可以更改它

Why javascript can't get the style value but can change it?

本文关键字:但可以 javascript 不能 获取 样式 为什么      更新时间:2023-09-26

我需要将标签数据传递给函数并在该函数中读取它,我尝试通过"this"传递标签,我可以更改一些样式元素,但我无法读取那里的样式数据。问题出在哪里

<!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>

元素上的 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>

相关文章: