我想使用jQuery将渐变或纯色应用于一个元素。为什么要用jQuery?因为这个网站有几种不同的颜色组合,所以生成CSS类会太麻烦。
假设我有一个由JSON调用生成的列表:
<div class="colours">
<ul>
<li class="black white"></li>
<li class="green"></li>
</ul>
</div>
如您所见,我需要一个带有渐变(黑色/白色)的列表元素和一个实心(绿色)的元素。
因此,我的问题是如何在一个列表类中设置渐变色,当需要两种颜色时或者仅需要一种颜色时设置实心颜色?
使用下面的代码时,当我尝试应用颜色时它总是给我“productHtml不是函数”或[object object]
。
$.each(data.product.custom, function(i, custom) {
var productsHtml = [];
$.each(custom.values, function(index, value){
var color = (value.title).toLowerCase();
var colorClean = color.replace(/\s?\/\s?/," ");
var colors = colorClean.split(/\s+/);
if (colors.length===1) {
colors[1] = colors[0];
}
// var productHtml = '' +
// '<li class="'+colorClean+'" ></li>';
var productHtml = $('<li></li>').css({
'background': '-moz-linear-gradient(-45deg, + colors[0] + 0%, + colors[0] + 49%, + colors[1] + 49%, + colors[1] + 100%)',
//etc etc
});
productsHtml.push(productHtml);
});
productsHtml = productsHtml.join('');
$('.product.'+id+' .colours').html('<ul>'+productsHtml+'</ul>');
});
我做错了什么?
'-moz-linear-gradient(-45deg, + colors[0] + 0%, + colors[0] + 49%, + colors[1] + 49%, + colors[1] + 100%)'
)可能是问题所在;你需要将变量与字符串连接起来(得到:'-moz-linear-gradient(-45deg,' + colors[0] + ' 0%', + colors[0] + '49%,' + colors[1] + '49%', + colors[1] + '100%)'
)。 - David Thomasbackground
行的末尾使用了,
? - Amit singh