截断文字的CSS选择器

时间:2018-10-11 16:54:54

标签: css html5 css-selectors

如果我的标签被截断了,有什么办法可以判断文本是否太长?这将有助于有条件地为剪贴文本添加其他样式。

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

这就是我想做的。

.truncate:truncated {
  color: red;
}

2 个答案:

答案 0 :(得分:1)

如果您不介意使用一些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>

答案 1 :(得分:1)

使用当前的CSS选择器/标准看起来是不可能的。