jQuery设置CSS背景不透明度 [英] jQuery set CSS background opacity

查看:609
本文介绍了jQuery设置CSS背景不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个< div> ,它的背景颜色(而不是其内容)的透明度我想更改。远程API向我发送此颜色:

  #abcdef 

我告诉jQuery(1.9)通过 .css


b $ b

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

结果div有 background-color #abcdef 的样式,而是其相同颜色的RGB表示。

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

(只是一个观察;不是问题的一部分)






项目需求已更改,现在我需要将背景的透明度更改为设置的百分比(50%)。因此,我所需的 background-color 属性是

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

但是,我找不到一种方法来设置这个背景颜色属性使用jQuery,一个十六进制颜色代码,并且仍然应用alpha值。 opacity 会影响div的内容以及背景,因此不是选项。

  $('div')。css('background-color','#abcdef')
.css('opacity',0.5); //不期望的不透明度更改为div的内容

给定字符串 #abcdef ,是否可以通过计算(例如hex2dec),如果我只能给一个十六进制颜色字符串,我将能够应用背景不透明的div

解决方案

尝试 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.

这篇关于jQuery设置CSS背景不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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