我有这个代码,它从十六进制代码生成RBG值。
<script>
var s = "<?php the_field('phpvariableforcolour'); ?>";
var patt = /^#([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})$/;
var matches = patt.exec(s);
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");";
alert(rgb);
</script>
我想将rgb变量(当前处于警报状态)应用于内嵌css样式,其中RGB值显示为例如rgba( 0,0,0 ,0.0): -
background-image: -webkit-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
background-image: -moz-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
background-image: -o-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
background-image: -ms-linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
background-image: linear-gradient(@origin, rgba(0,0,0,0.0), rgba(0,0,0,0.2));
我无法找到一种方法来实现这一点,使用jQuery我可以添加背景图像,但不是所有这些。
答案 0 :(得分:3)
您可以在jQuery中使用“.css()”函数。
http://jsbin.com/vukize/1/edit?js,output
我使用的HTML:
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<meta charset="utf-8">
<title>jQuery inline RGB Values</title>
</head>
<body>
<div id="colorObject"></div>
</body>
</html>
jQuery:
var rgba = "rgba(110,131,37,0.5)";
var rgbaTwo = "rgba(10,131,37,1)";
$('#colorObject').css({
'background' : '-webkit-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
'background' : '-moz-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
'background' : '-o-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
'background' : '-ms-linear-gradient(left,' + rgba + ', ' + rgbaTwo + ')',
'background' : 'linear-gradient(to right,' + rgba + ', ' + rgbaTwo + ')'
});
编辑: 看起来有几个人打败了我。 ;)
双重编辑:
所以,似乎问题是分号,如果它被用在css();
函数中,它就不应该是分号。
变化:
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+");";
为:
var rgb = "rgb("+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+")";
现在将它用作css();
函数中的变量将起作用。
答案 1 :(得分:1)
无法将javascript变量值分配给css属性。
对于你的情况,最好的解决方案是使用.css它是这样的:
$(your-selector).css({
background: "-webkit-gradient(linear, left top, left bottom, from("+rgb+"), to(#ccc))"
....
});
答案 2 :(得分:0)
您可以使用$('el').css("background-image","value");
类似的东西:
var rgb = ""+parseInt(matches[1], 16)+","+parseInt(matches[2], 16)+","+parseInt(matches[3], 16)+"";
$('el').css("background-image","linear-gradient(@origin, rgba("+rgb+",0.0), rgba("+rgb+",0.2)");