jQuery是否会自动将RGBA转换为RGB?

6
我是jQuery的新手,有点惊讶:当我写


$('#selected-color').css('background-color', 'rgba(0,0,0,1)');

我的最终样式#selected-color的颜色是rgb(0,0,0),这会在我获取背景颜色并尝试应用正则表达式时产生很大的差异,因为我期望得到一个rgba字符串。
所以问题是,当alpha设置为1时,Jquery是否对rgba值应用自动转换?我使用a=1.0也得到了相同的结果,但是a=0.99时得到了RGBA。在jquery文档中没有关于这方面的成功指示。

1
不是jQuery的问题;当我使用原生JavaScript时,我得到了相同的结果。 - user5734311
使用 a = 1 没有任何意义,这就是为什么它被 JavaScript 替换的原因。任何影响透明度的值都可以正常工作。 - Anand Singh
1个回答

0

这不是 jQuery 的特性。当 alpha = 1 时,所有颜色表达式都会被计算为 rgb 表达式,而当 alpha < 1 时,则会被计算为 rgba 表达式。

来自 MDN 文档

计算值:如果该值是半透明的,则计算值将是相应的 rgba() 值。如果它不是,则将是相应的 rgb() 值。transparent 关键字映射到 rgba(0,0,0,0)。

CSS3 规范 中:

计算值:

  • 基本颜色关键字、RGB十六进制值和扩展颜色关键字的计算值是相当于数字RGB值的三元组,例如六位十六进制值或rgb(...)函数值,带有alpha值为1。
  • 关键字“transparent”的计算值是所有零数值RGBA值的四元组,例如rgba(0,0,0,0)。
  • 对于所有其他值,计算值是指定的值。

示例:

var
  foo = document.getElementById("foo"),
  getBGColor = function () {
    return getComputedStyle(foo, null).backgroundColor;
  };

/* Setting the background with an alpha value of 1. */
foo.style.backgroundColor = "rgba(0, 0, 0, 1)";
console.log("alpha = 1: ", getBGColor());

/* Setting the background with a hex number. */
foo.style.backgroundColor = "#000";
console.log("alpha = 1: ", getBGColor());

/* Setting the background with a hsl expression. */
foo.style.backgroundColor = "hsl(120, 100%, 25%)";
console.log("alpha = 1: ", getBGColor());

/* Setting the background with an alpha value less than 1. */
foo.style.backgroundColor = "rgba(0, 0, 0, .5)";
console.log("alpha < 1: ", getBGColor());

/* Setting the background with a hsla expression. */
foo.style.backgroundColor = "hsla(120, 100%, 25%, .5)";
console.log("alpha < 1: ", getBGColor());
<div id = "foo"></div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接