我有一个网站的颜色主题,我正在处理刷新时的更改,并希望在我的 HTML 中显示 css 背景颜色属性。这可能吗?
即
<footer>The color of the moment is <insert the background color attribute>. Refresh for a makeover</footer>
会显示类似的东西
“当下的颜色是#DB0C0C。焕然一新”
由于十六进制颜色根据加载的样式表而变化,我不想对其进行硬编码。如果我有一个 ruby 变量 @color which = #ff0000 并想在 html 中显示它,我可以做类似
<%= @color%>
我想知道是否有任何方法可以做类似访问 CSS 属性的事情。
最佳答案
为此你甚至不需要 jQuery.. 你可以只使用 vanilla javascript 和 .getComputedStyle()
:
<span id='color-map'></span>
var element = document.getElementById("id-goes-here");
var style = window.getComputedStyle(element);
document.getElementById('color-map').innerHTML = style.backgroundColor;
但是,这似乎并没有以十六进制形式给出颜色,而是给出了一个 'rpg(x, y, z)' 字符串。要从中获取十六进制,您可以使用正则表达式解析它并返回结果:
function rgbsToHex(str) {
var hex = "#";
var matches = str.match(/rgb\((\d+),\s(\d+),\s(\d+)\)/);
hex += Number(matches[1]).toString(16);
hex += Number(matches[2]).toString(16);
hex += Number(matches[3]).toString(16);
return hex;
}
关于css - 在 HTML 中嵌入 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029945/