object.style.color只返回rgb [英] does object.style.color only return rgb

查看:79
本文介绍了object.style.color只返回rgb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:JavaScript
object.style.color返回类似
rgb(255,0,0)
Is有另一种返回格式,比如十六进制?

environment: JavaScript object.style.color returns something like "rgb(255,0,0)" Is there another return format, like hex?

var colorvariable = document.getElementById('text1').style.color


推荐答案

如果你设置:

document.getElementById('text1').style.color = '#000';

它将返回#000

但是,如果你设置:

document.getElementById('text1').style.color = 'rgb(0,0,0)';

它将返回 rgb(0,0,0),所以此返回值取决于设置的值。

It will return rgb(0,0,0), so this returned value depends on the value that was set.

您可以使用 getComputedStyle 来获取RGB格式的颜色,然后转换为HEX。看到这段代码:

You can use getComputedStyle to get the color in RGB format and then convert to HEX. See this code:

var hexChars = '0123456789ABCDEF';
var rgb = getComputedStyle(document.body).color.match(/\d+/g);
var r = parseInt(rgb[0]).toString(16);
var g = parseInt(rgb[1]).toString(16);
var b = parseInt(rgb[2]).toString(16);
var hex = '#' + r + g + b;

这篇关于object.style.color只返回rgb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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