【问题标题】:Embed CSS attribute in HTML在 HTML 中嵌入 CSS 属性
【发布时间】:2013-04-08 10:32:07
【问题描述】:

我正在处理的网站的颜色主题在刷新时会发生变化,并希望在我的 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 属性的操作。

【问题讨论】:

  • 有什么原因不能直接写进去吗?
  • 然后根据您的编辑,您需要的是 javascript。否则没有纯粹的 css/html 方法来获取该值。

标签: css html less


【解决方案1】:

你甚至不需要 jQuery。你可以只使用带有 .getComputedStyle() 的 vanilla javascript:

<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

【讨论】:

    【解决方案2】:

    您可以在 jQuery 中使用 .css() 函数。

    $('footer').find('span').text($('.bg').css('background-color'));
    

    这将为您提供 rgb 格式的颜色,如果您想以 HEX 格式显示,请查看this 了解更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-26
      • 2014-03-28
      • 2015-07-30
      • 2015-08-02
      • 2021-12-18
      • 2021-09-24
      • 1970-01-01
      相关资源
      最近更新 更多