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

标签 javascript dom

我需要将标签数据传递给函数并在该函数中读取它, 我尝试通过“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: ..."

要获取元素的计算样式,可以使用getCompulatedStyle函数(在任何现代元素上)或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>

关于javascript - 为什么javascript无法获取样式值但可以更改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27175115/

相关文章:

javascript - 返回站点地图 url

php - Symfony2 DomCrawler 从 DOMElement 移除节点

Javascript、Jquery、DOM

javascript - 在 javascript 中查找上下文相关的子字符串

javascript - 每次都需要我们的应用程序模块在控制台中进行调试的替代方案

javascript - 通过导航 Prop 传递状态

javascript - 如何在智能电视浏览器上对我的网站进行故障排除?

javascript - 递归函数中的 Array.prototype.reduce 产生意外结果

php - 匹配 “img” 标签和 “alt” 标签和行号之间的字符串

javascript - 使用 .filter() 使用 jQuery 选择包含带有特定文本的 tr 的表行