gpt4 book ai didi

jquery - 为什么 jQuery 用 rgb() 代替 hsl()?

转载 作者:行者123 更新时间:2023-12-01 03:08:10 25 4
gpt4 key购买 nike

我想动态添加一些跨度,并将 hsl 背景颜色应用于样式属性,如下所示:

<span style="background-color: hsl(190, 75%, 43%)"></span>

这是我的 jQuery 执行此操作的方法:

var hues = [ 172, 178, 184, 190, 196, 202, 208 ];

$.each(hues, function(index, backgroundHue) {
var newSpan = $('<span></span>');
newSpan.css('background-color', 'hsl('+backgroundHue+', 75%, 43%)');
someBlock.append(newSpan);
});

但结果我得到了带有 rgb() 背景颜色的跨度(从 hsl() 自动转换而来):

<span style="background-color: rgb(27, 165, 192);"></span>

这是一个 fiddle :https://jsfiddle.net/pbjcvwdh/5/

谁能解释一下为什么会这样,有什么方法可以避免这种自动转换吗?如果我在 html 中静态应用背景颜色,它不会更改为 rgb()。

最佳答案

jQuery 与此行为无关 - 这只是因为浏览器以 RGB 格式呈现值。不幸的是你无法改变它。如果您想获取 HSL 格式的值,您需要将其从 RGB 转换回来。 This question如果需要,可以帮助您。

为了证明上述内容,这里有一个表现出相同行为的原生 JS 实现:

[172, 178, 184, 190, 196, 202, 208].forEach(function(backgroundHue) {
var span = document.createElement('span');
span.style.backgroundColor = 'hsl(' + backgroundHue + ', 75%, 43%)';
document.querySelector('.add-em-here').appendChild(span);
});
.add-em-here span {
display: inline-block;
height: 40px;
width: 40px;
border: 2px solid white;
margin-left: 6px;
}
<div class="add-em-here">
<!-- Added statically - stays with hsl() -->
<span style="background-color: hsl(60, 75%, 43%)"></span>

<!-- Added dynamically - auto-replaced with rgb() -->
</div>

关于jquery - 为什么 jQuery 用 rgb() 代替 hsl()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40380297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com