且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

jQuery设置CSS背景不透明度

更新时间:2022-10-19 13:12:51

尝试 parseInt(hex,16)将十六进制字符串转换为十进制int

所以在这种情况下,它将是:

  var color = #abcdef'; 
var rgbaCol ='rgba('+ parseInt(color.slice(-6,-4),16)
+','+ parseInt(color.slice(-4,-2),16 )
+','+ parseInt(color.slice(-2),16)
+',0.5)';
$('div')。css('background-color',rgbaCol)

您应该创建一个函数,以便在您的应用程序中使用。


I have a <div> whose transparency of its background-color (and not its contents) I'd like to change. A remote API sends me this colour:

#abcdef

and I tell jQuery (1.9) to apply this colour via .css:

$('div').css('background-color', '#abcdef');

The resultant div has a background-color style of not #abcdef, but rather its RGB representation of the same colour.

background-color: rgb(171, 205, 239);

(Just an observation; not part of the problem)


The project requirement has been changed such that I will now need to change the transparency of the background as well, to a set percentage (50%). My desired background-color attribute is thus

background-color: rgba(171, 205, 239, 0.5);

, however, I cannot find a way to set this background-color attribute using just jQuery, a hex colour code, and still apply an alpha value. opacity affects contents of the div as well as the background, so it is not an option.

$('div').css('background-color', '#abcdef')
        .css('opacity', 0.5);  // undesirable opacity changes to div's content

Given the string #abcdef, is it possible only by calculation (e.g. hex2dec) that I will be able to apply a background opacity to a div if I am given only a hex colour string?

try parseInt(hex,16) to convert hex string into decimal int

so in this case it'll be:

var color = '#abcdef';
var rgbaCol = 'rgba(' + parseInt(color.slice(-6,-4),16)
    + ',' + parseInt(color.slice(-4,-2),16)
    + ',' + parseInt(color.slice(-2),16)
    +',0.5)';
$('div').css('background-color', rgbaCol)

you should create a function out of this to use in your application.