css - 截断文本的 CSS 选择器
问题描述
如果我有一个截断的标签,有什么方法可以判断文本是否太长?这将有助于有条件地为剪辑文本添加额外的样式。
.truncate {
width: 250px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
这是我希望能够做到的。
.truncate:truncated {
color: red;
}
解决方案
如果您不介意使用一点 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>
推荐阅读
- spring-boot - 使用外部 tomcat 在 Spring Boot 应用程序中定义信任库和密钥库信息
- c# - C# - UWP AppInfo 抛出 NotImplementedException
- python - tf.train.Checkpoint 是否正在恢复?
- web-scraping - Power BI:获取数据 - 无法连接 - 详细信息:“禁止访问资源。”
- python-3.x - on_guild_channel_update 在最新更新中被忽略
- ios - 无法符号化崩溃日志
- css - Safari Web Inspector 自动完成 CSS
- python - 如果数字太小,例如 pow(1e+15+1,1/3),为什么我无法以浮点数的精度得到 python 的正确答案
- sqlite - 多对多关系中不需要的唯一约束
- javascript - jQuery 下拉菜单