我正在尝试使用jquery应用渐变或纯色到元素。为什么使用jQuery?因为这个网站有几个不同的颜色组合,所以生成css类是太多的工作。
假设我有一个JSON调用生成的列表
<div class="colours">
<ul>
<li class="black white"></li>
<li class="green"></li>
</ul>
</div>
正如你所看到的,我需要一个带有渐变(黑色/白色)的列表元素和一个纯色(绿色)元素。
所以我的问题是如何设置渐变当一个列表类有两种颜色在它或纯色时,只需要一种颜色?
当我尝试应用颜色时,下面的代码总是给我"producthhtml不是一个函数"或[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>');
});
我做错了什么?
下面是使用data属性的解决方案。
- 首先,我遍历. colors 中的所有元素。
- 然后找到它的data- color 属性。
- 用必要的线性梯度信息创建一个字符串
- 在其data属性中添加所有颜色(以","分隔)
- 关闭线性梯度信息字符串
- 将线性梯度应用于
css()
的css规则。
注释它可以有任何颜色值:
-
data-colour("rgb(255,123,43)");
-
data-colour("#222 #546");
-
data-colour("rgb(2,150,255) #3a1");
$(".colours").find('li').each(function(index, e) {
var $elem = $(e);
var colourattri = $(this).data("colour");
var colours = colourattri.split(",");
if (colours.length >= 2) {
var linear = "linear-gradient(90deg, ";
for (var index in colours) {
linear += colours[index];
if (index != colours.length - 1) {
linear += ", ";
}
}
linear += ")";
$elem.css({
background: linear,
});
} else if (colours.length == 1) {
$elem.css("background-color", colours[0]);
}
});
li {
padding: 20px;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="colours">
<ul>
<li data-colour="black">Some text here</li>
<li data-colour="black, white">Some text here</li>
<li data-colour="red, blue">Some text here</li>
<li data-colour="pink, white">Some text here</li>
<!-- This can take a lot of colours-->
<li data-colour="red, Orange, green, blue, indigo, violet">Some text here</li>
<li data-colour="rgb(22,150,255), red, #2c3">Some text here</li>
<li data-colour="rgb(22,150,255) 50%, red 60%, #2c3 90%">Some text here</li>
</ul>
</div>
我建议单独阅读每种颜色,然后应用渐变/纯色逻辑。如:
$('li').each(function(){
var classNames = $(this).attr("class").toString().split(' ');
$.each(classNames, function (i, className) {
// do solid color or gradient
});
});