简体   繁体   English

以十六进制设置背景颜色

[英]Set background color in hex

How to set elements background color as hex value in JavaScript?如何在 JavaScript 中将元素背景颜色设置为十六进制值? backgroundColor method sets only in rgb. backgroundColor方法仅在 rgb 中设置。

square.style.backgroundColor = input_color; input_color is #123456, but in the source sets rgb(18, 52, 86) input_color是#123456,但在源代码中设置了rgb(18, 52, 86)

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 的例子

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

Here is an example .这是一个例子

找到了一些应该工作的东西:

document.getElementById('square').attributes['style'].textContent='background-color:'+ input_color 

Method backgroundColor supports hex value and others too.方法backgroundColor支持十六进制值和其他值。 You can use square.style.backgroundColor = '#FF0000' .您可以使用square.style.backgroundColor = '#FF0000'

Here is the code snippet that demonstrates it:这是演示它的代码片段:

 document.getElementById('square').style.backgroundColor = '#FF0000';
 <div id="square" style="background-color: rgb(0, 255, 0); width: 50px; height: 50px"></div>

If you want hex, you can set it as a string such as '#123456', or you can use hex numbers rgb (0x12, 0x34, 0x56) .如果需要十六进制,可以将其设置为字符串,例如 '#123456',也可以使用十六进制数字rgb (0x12, 0x34, 0x56) Does that answer your question?这是否回答你的问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM