首页 > 解决方案 > 截断文本的 CSS 选择器

问题描述

如果我有一个截断的标签,有什么方法可以判断文本是否太长?这将有助于有条件地为剪辑文本添加额外的样式。

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

这是我希望能够做到的。

.truncate:truncated {
  color: red;
}

标签: csshtmlcss-selectors

解决方案


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


推荐阅读