使用HEX设置背景颜色

问题描述 投票:1回答:2

当我使用jQuery(或者,就此而言,纯JavaScript)将样式颜色或背景颜色设置为HEX颜色时,它似乎会自动将其转换为RGB等效颜色。

我如何能够将样式设置为HEX颜色并在HTML中保留相同的HEX颜色(而不是将其转换为RGB等效颜色)。

见这里:http://jsfiddle.net/cuhd8bgL/9/

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

enter image description here

javascript jquery
2个回答
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>

0
投票

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

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


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

document.getElementById('whatever').attributes['style'].textContent='background-color:#3282c3'
© www.soinside.com 2019 - 2024. All rights reserved.