gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:44:59 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com