javascript 以十六进制设置背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13712697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set background color in hex
提问by Kin
How to set elements background color as hex value in JavaScript? backgroundColor
method sets only in rgb.
如何在 JavaScript 中将元素背景颜色设置为十六进制值?backgroundColor
方法集仅在 rgb 中。
square.style.backgroundColor = input_color;
input_color
is #123456, but in the source sets rgb(18, 52, 86)
square.style.backgroundColor = input_color;
input_color
是 #123456,但在源集中 rgb(18, 52, 86)
回答by pandavenger
A better solution to your problem would be just to set the background color like this
解决您的问题的更好方法就是像这样设置背景颜色
square.style.backgroundColor = "rgb(12,34,56)";
Otherwise I would use Sheika's example
否则我会用 Sheika 的例子
回答by The Alpha
If you want to get the color of an element which is in rgb
format then you can convert it from rgb
to hex
format
如果您想获取rgb
格式中元素的颜色,则可以将其转换rgb
为hex
格式
function rgbToHex(col)
{
if(col.charAt(0)=='r')
{
col=col.replace('rgb(','').replace(')','').split(',');
var r=parseInt(col[0], 10).toString(16);
var g=parseInt(col[1], 10).toString(16);
var b=parseInt(col[2], 10).toString(16);
r=r.length==1?'0'+r:r; g=g.length==1?'0'+g:g; b=b.length==1?'0'+b:b;
var colHex='#'+r+g+b;
return colHex;
}
}
Call the function
调用函数
var col=document.getElementById('myDiv').style.backgroundColor;
alert(rgbToHex(col)); // alerts hex value
回答by Domotor Zsolt
Found something that should work:
找到了一些应该工作的东西:
document.getElementById('square').attributes['style'].textContent='background-color:'+ input_color
回答by Bas Wijnen
If you want hex, you can set it as a string such as '#123456', or you can use hex numbers rgb (0x12, 0x34, 0x56)
. Does that answer your question?
如果需要十六进制,可以将其设置为字符串,例如 '#123456',也可以使用十六进制数字rgb (0x12, 0x34, 0x56)
。这是否回答你的问题?