使用十六进制设置背景颜色

时间:2018-09-02 16:38:58

标签: javascript jquery

当我使用jQuery(或纯JavaScript)将样式颜色或背景色设置为十六进制颜色时,似乎会自动将其转换为与RGB等价的颜色。

如何将样式设置为十六进制颜色并在HTML中保留相同的十六进制颜色(而不是将其转换为等效的RGB)。

请参阅此处: http://jsfiddle.net/cuhd8bgL/9/

$(function ()
{
    $("div").css("color", "#3282c3");
});

enter image description here

2 个答案:

答案 0 :(得分:2)

我建议.attr( attributeName, function )CSSStyleDeclaration.removeProperty()改用正则表达式:

$("div").attr('style', function() {
  this.style.removeProperty('color'); // remove color if exist....
  return this.style.cssText + 'color:#3282c3;'; // add your color
});
$("div").each(function() {
  console.log(this.outerHTML);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="font-family: Helvetica;line-height: 100%;margin-top: 20px; text-align: left;vertical-align: bottom;color: blue">
    I want a hex color! (I have already a style prop...)
</div>
<div>
    I want a hex color!
</div>

答案 1 :(得分:0)

语法rgb(r, g, b)只是#RRGGBB的替代形式。没有功能上的差异。

因此,浏览器可能根本不会存储用于指定颜色并返回任何表示形式的语法。


但是,如果您确实要具有十六进制值,则唯一的选择是绕过所有样式对象并直接分配属性值。示例:

document.getElementById('whatever').attributes['style'].textContent='background-color:#3282c3'