在动态元素上应用渐变或纯色

4

我想使用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 Thomas
为什么在 background 行的末尾使用了 , - Amit singh
在连字符内部的变量将不会被Javascript计算。请使用字符串连接符“+”。 - connexo
这看起来比编辑、扩展或重置CSS要痛苦得多。 - lharby
2个回答

5
以下是使用data-attribute的解决方案。
  1. 首先,我遍历所有在.colours中的li元素。
  2. 然后找到它的data-colour属性。
  3. 创建一个包含必要线性渐变信息的字符串。
  4. 将其数据属性中的所有颜色(用逗号隔开)添加到字符串中。
  5. 结束线性渐变信息字符串。
  6. 使用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>


好的,这正是我在寻找的!只有一件事...是否可以设置例如50%的白色和50%的黑色?这样你就会得到与普通的CSS规则linear-gradient(135deg, #000000 0%,#000000 49%,#ffffff 49%,#ffffff 100%);相同的效果。 - Meules
你试过了吗?噢,好吧,我猜我会为你更新它。 - Persijn
代码完美运行,唯一需要的是每种颜色需要是50%,而不是真正的渐变。 - Meules
现在它会根据“,”而不是空格进行分割。 - Persijn
好的,我理解你的做法了(我想);)... 你从类名中获取的颜色例如是“黑色”等等... 我之前的问题实际上是如何将50%添加到那个类名,以便它读取 linear-gradient(135deg,#000000 0%,#000000 49%,#ffffff 49%,#ffffff 100%);??我不能自己添加,因为类名是动态生成的... - Meules
如果你要添加百分比,那么如果你要将它添加到类中,就会变得非常棘手和不可靠。请改为将其添加到数据属性中。 - Persijn

0

我建议逐个阅读每种颜色,然后应用你的渐变/纯色逻辑。例如:

$('li').each(function(){
    var classNames = $(this).attr("class").toString().split(' ');
    $.each(classNames, function (i, className) {
        // do solid color or gradient
    });
});

我还没有完全理解...这些类名是动态生成的吗??! 还是这是在 json 调用之后执行的 "函数" ...你能再解释一下吗? - Meules
不,它只是在每个列表项中循环遍历类名。 - raduation

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接