【问题标题】:CSS class depending on list items text lengthCSS 类取决于列表项文本长度
【发布时间】:2011-05-20 08:48:30
【问题描述】:

有没有办法根据值的长度为列表中的项目设置不同的类?最好是纯 JS 或 jQuery。

我有一个固定宽度的列表,每个列表项中的文本量各不相同。列表项的背景不能重复或扩展,因此我需要为不同的文本长度制作不同的背景(类)。

1-15 个字符将由默认 css 类处理,15-30 个字符需要一个具有扩展背景的额外类,30-45 个字符需要另一个类等。

作为 JS 中的一个总 n00b,我无法弄清楚这一点,即使我在过去两天一直在摆弄它......

非常感谢,

埃里克。

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:
    $('#myList li').each(function() {
        var length = ($(this).html().length);
    
        if (length > 30) {
            $(this).addClass('longest');
        }
        else if (length > 15) {
            $(this).addClass('long');
        }
        else {
            $(this).addClass('default');
        }  
    });
    

    工作示例here

    【讨论】:

    • 非常感谢,我欠你一杯啤酒!
    【解决方案2】:
    $('.listItem').each(function(){
      var content = $(this).html();
      if(var.length > 30){
         $(this).addClass('Over30');
      }
       .....etc
    

    将其设置为在内容加载后运行,例如

     $(document).ready(function () {
       $('.listItem').each(function(){
         var content = $(this).html();
         if(var.length > 30){
            $(this).addClass('Over30');
         }
       .....etc
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-14
      • 1970-01-01
      • 2011-11-12
      相关资源
      最近更新 更多