代码之家  ›  专栏  ›  技术社区  ›  Swazimodo

截断文本的CSS选择器

  •  0
  • Swazimodo  · 技术社区  · 6 年前

    如果我有一个被截断的标签,有没有办法判断文本是否太长?这将有助于有条件地为剪裁文本添加其他样式。

    .truncate {
      width: 250px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    

    这就是我想做的。

    .truncate:truncated {
      color: red;
    }
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   Mr Lister hawi    6 年前

    如果您不介意使用一点JavaScript,那么解决方案就是微不足道的。
    不确定是否有非javascript解决方案。

    var divs = document.querySelectorAll('.truncate');
    for (var i = 0; i < divs.length; ++i)
      if (divs[i].scrollWidth > divs[i].clientWidth)
        divs[i].classList.add('truncated');
    .truncate {
      width: 250px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .truncate.truncated { /* note the dot here instead of a colon */
      color: red;
    }
    <div class="truncate">
      This is the content
    </div>
    <div class="truncate">
      This is the content that is far longer than the container
    </div>
        2
  •  0
  •   Swazimodo    6 年前

    看起来这在当前的CSS选择器/标准中是不可能的。

    推荐文章