将jQuery变量放入CSS渐变中

问题描述 投票:1回答:3

我有此代码可从十六进制代码生成RGB值。

            <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变量(当前处于警报状态)应用于RGB值显示在其中的内联CSS样式,例如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我可以添加背景图像,但不能添加所有这些。

jquery variables transparency rgb gradient
3个回答
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
投票

无法将javascript变量值分配给CSS属性。

对于您而言,最好的解决方案是使用.css,就像这样:

$(your-selector).css({
  background: "-webkit-gradient(linear, left top, left bottom, from("+rgb+"), to(#ccc))"
  ....
});
  • 将(@左上,左下)更改为(@origin)值。

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)");

有关更多信息:http://api.jquery.com/css/

© www.soinside.com 2019 - 2024. All rights reserved.