目前我想通过 javascript 读出 css 的背景颜色,以用所需的颜色更新 Canvas 。到目前为止,我通过在 html 中创建一个 dummy 对象来使其工作,该对象包含我可以从中读取的 css:
CSS 内容:
.logmessage-debug {
color: #fff;
background-color: #999999;
}
.logmessage-info {
color: #fff;
background-color: #5cb85c;
}
.logmessage-warn {
color: #fff;
background-color: #f0ad4e;
}
.logmessage-error {
color: #fff;
background-color: #d9534f;
}
.logmessage-fatal {
color: #fff;
background-color: #d955d9;
}
HTML 部分:
<canvas id="myCanvas" width="200" height="200"></canvas>
<!-- The dummy objects allowing access to the css properties -->
<div id="debug" class="logmessage-debug"></div>
<div id="info" class="logmessage-info"></div>
<div id="warn" class="logmessage-warn"></div>
<div id="error" class="logmessage-error"></div>
<div id="fatal" class="logmessage-fatal"></div>
<script type="text/javascript">
updateCanvas();
</script>
JavaScript 部分:
function updateCanvas() {
$.ajax({
url: "api/myWebService",
success: function (severityLevel) {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = getSeverityColorFromStyle(severityLevel);
ctx.fillRect(0, 0, c.clientWidth, c.clientHeight);
},
complete: function() {
setTimeout(updateCanvas, 2000);
}
})
}
function getSeverityColorFromStyle(styleName) {
// Any other way to read the css background color
// directly instead of asking the dummy object?
return $("#" + styleName).css("background-color");
}
到目前为止,上述方法按预期工作,我可以得到我喜欢的所需颜色。但是添加这些虚拟对象只是为了访问所需的 css 值让我感到不舒服。是否存在从 css 中检索这些值的直接方法?
最佳答案
您可以创建一个循环遍历页面上所有样式表/规则并尝试匹配它的函数
function getStyle(className) {
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
for(var x=0;x<classes.length;x++) {
if(classes[x].selectorText==className) {
return (classes[x].cssText) ? classes[x].cssText : classes[x].style.cssText;
}
}
}
有关更多详细信息,请参阅之前的帖子 How do you read CSS rule values with JavaScript?
关于javascript - 通过 javascript 检索 CSS 属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20948736/