使用JavaScript获取HSL颜色 [英] Get hsl color with javascript

查看:391
本文介绍了使用JavaScript获取HSL颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个:

.box{
  color: #FF3010;
  background: hsl(0,90%,40%);
}

然后是这个

var box = document.querySelector(".box");
var result = document.querySelector(".result");
result.innerHTML = "BG color: "+window.getComputedStyle(box).backgroundColor;
result.innerHTML += "<br>";
result.innerHTML += "color:"+window.getComputedStyle(box).color;

问题是它总是在rgb中打印值.所以,我有2个问题:

  1. 是否有可能获得css中编写的值?
  2. 是否可以将颜色强制为hsl而不是rgb?

解决方案

您有两种方法可以获取dom元素(不是css)的实时样式,但不能获取hsl,而只能获取rgb/rgba字符串.

>

 var style = window.getComputedStyle(element).getPropertyValue('background-color')

var style = cell.computedStyleMap().get('background-color').toString();
 

问您的问题:

  1. 您可以通过两种方式获得它:

    a.使用CSSAPI.您可以在mdn上查看文档.

    b.使用mutationobserver,如果值被某些更改,则可以从oldvalue获取它.

  2. 您不能直接获取hsl,但是可以通过上述两种方法获取rgb.然后将其更改为hsl,如果您的hsl与html格式匹配,则可以直接使用hsl. html格式的hsl不是[0-1],而是h是[0-360],而s& l与%.

顺便说一句,我只是尝试在Web中使用HSL,但这与现实不符.黄色比紫色浅,绿色比蓝色浅. rgb(0,255,0)比(123,0,123)更轻,尽管最后一个比hsl中的上述内容更轻.

If I have this:

.box{
  color: #FF3010;
  background: hsl(0,90%,40%);
}

and then this:

var box = document.querySelector(".box");
var result = document.querySelector(".result");
result.innerHTML = "BG color: "+window.getComputedStyle(box).backgroundColor;
result.innerHTML += "<br>";
result.innerHTML += "color:"+window.getComputedStyle(box).color;

The problem is that it always prints the values in rgb. So, I have 2 questions:

  1. Is it posible to get the value as written in the css?
  2. Is it posible to force the color to be hsl instead of rgb?

解决方案

you have two method get the live style of a dom element(not css), but you can not get hsl, but only rgb/rgba string.

var style = window.getComputedStyle(element).getPropertyValue('background-color')

var style = cell.computedStyleMap().get('background-color').toString();

ask your question:

  1. you can get it from two way:

    a. use CSSAPI. you can see doc on mdn.

    b. use mutationobserver, you can from oldvalue get it, if the value be changed by something.

  2. you can not get hsl directly, but you can get rgb by two way as above. and than change them to hsl, and if your hsl is match the html format, you can use hsl directly. the html format hsl not [0-1], but h is [0-360], and s & l with the %.

btw i just try to use hsl in web, but it is not match reality. yellow is more lighter than purple, and green is more lighter than blue. rgb(0, 255, 0) is more more lighter than (123, 0, 123), although the last is lighter than the above in hsl.

这篇关于使用JavaScript获取HSL颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆