javascript - jquery 会自动将 rgba 转换为 rgb 吗?

标签 javascript jquery rgb rgba

<分区>

我是 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 文档中没有关于此的成功指示

最佳答案

这不是 jQuery特征。所有颜色表达式都计算为 rgb alpha = 1 时的表达式并进入 rgba alpha < 1 时的表达式.

来自 MDN Documentation :

Computed value: If the value is translucent, the computed value will be the rgba() corresponding one. If it isn't, it will be the rgb() corresponding one. The transparent keyword maps to rgba(0,0,0,0).

CSS3 SPEC :

Computed value:

  • The computed value for basic color keywords, RGB hex values and extended color keywords is the equivalent triplet of numerical RGB values, e.g. six digit hex value or rgb(...) functional value, with an alpha value of 1.
  • The computed value of the keyword ‘transparent’ is the quadruplet of all zero numerical RGBA values, e.g. rgba(0,0,0,0).
  • For all other values, the computed value is the specified value.

示例:

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>

关于javascript - jquery 会自动将 rgba 转换为 rgb 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51628684/

相关文章:

javascript - 我需要获得值的总和

javascript - jQuery UI 菜单栏,位置子菜单绝对左侧

javascript - 如何显示十六进制颜色onclick对应的colorbox Javascript?

javascript - 为什么这个 bootstrap carousel slider 不滑动?

java - Java中从RGB到HSV(Color.RGBtoHSB)返回不同的结果

javascript - 元素的高度 javascript

javascript - 无法删除标签 gmail api

jquery - 如何在不使用任何 jQuery CSS 的情况下设置 jQueryUI Datepicker 的样式

python - 图像的 RGB 立方体

php - 在 PHP/jQuery 中从十六进制代码或 RGB 生成渐变?