为什么javascript不能获取样式值,但可以更改它
Why javascript can't get the style value but can change it?
我需要将标签数据传递给函数并在该函数中读取它,我尝试通过"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>
相关文章:
- Javascript赢得'不能在IE上编译,但可以在Chrome上运行
- 无法使用JavaScript在iPhone上播放声音,但可以在Android上播放
- 无法使用“;测试”;作为javascript中的值,但可以使用像1这样的数字
- Javascript:输入框-自动大写第一个字母,但可以重写
- 如何使元素鼠标不可点击,但可以通过javascript单击
- 为什么javascript不能获取样式值,但可以更改它
- 纯Javascript可以获取所有span元素,但可以通过定义的类进行特定的编辑
- 如何让两个圆石互相交谈.最好在Pebble.js中使用javascript,但可以使用PebbleKit sdk或Sta
- 我可以将HTML片段存储在不同的文件中,但可以通过JavaScript访问吗
- 通过DOM工作将PHP变量传递给JavaScript,但可以't将相同的变量从JS传递回PHP
- javascript代码不能在本地正确执行,但可以在JS Fiddle中工作
- 无法通过JavaScript发送数据库时间戳,但可以发送其他值
- 为什么单行异或交换不能在Javascript中工作,但可以在c++中工作
- javascript中的POST请求失败,但可以在fiddler中看到成功的响应
- javascript onclick不能在chrome和IE8中工作,但可以在firefox 7.0.1中工作
- 使用签名URL上传到Amazon S3可以在curl中工作,但在javascript中不行
- 现场Javascript不能在Electron中工作,但可以在其他任何地方工作
- 我KISS(保持简单,愚蠢),但这个JavaScript结构可以改进吗
- JavaScript不能在IE中工作,但可以在FireFox中工作
- 为什么我不能在.net中创建COM对象,但可以在JavaScript中创建