【发布时间】:2020-03-13 01:18:24
【问题描述】:
需要替换第一个或第二个渐变色,像这样:
var x = 1;
var new_color = 'rgb(140,220,0)';
var sty = $('#targ').attr('style');
if(x == 1){
var first_rgb = '???'; // regex here to get `rgb(255,102,255)`
var new_sty = sty.replace(first_rgb, new_color);
}
else{
var second_rgb = '???'; // regex here to get `rgb(255,0,0)`
var new_sty = sty.replace(second_rgb, new_color);
}
$('#targ').attr('style', new_sty)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="targ" style="background:linear-gradient(to right, rgb(255,102,255), rgb(255,0,0)); color:black; padding:25px 9px 14px 9px;">LOREM</div>
有什么帮助吗?
【问题讨论】:
-
为什么不直接使用
sty.replace('rgb(255,102,255)', new_color); -
@Nick - rgb... 是一个变量
标签: javascript jquery regex