css - 在 HTML 中嵌入 CSS 属性

标签 css html less

我有一个网站的颜色主题,我正在处理刷新时的更改,并希望在我的 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;
}

DEMO

关于css - 在 HTML 中嵌入 CSS 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16029945/

相关文章:

javascript - 摆脱链接标签?

css - 如何在我编译的 LESS css 文件中获得正确的相对路径?

html - 不可移植的 CSS : button background images do not display in some mobile browsers

jquery - 如果浏览器不支持 css3,如何提供不同的样式表?

html - 表中的最后一个标题和列应该是可滚动的

javascript - 选择 iframe 中元素的 iframe 父级,在 iframe 之外执行

python - 通过 Django 模板检测模板中使用的语言

css - 如何在 less 中创建列表输出?

javascript - 谷歌地图显示为灰色,但在调整浏览器大小时有效

html - 我可以禁用 HTML 中的地址链接吗?