zl程序教程

您现在的位置是:首页 >  其他

当前栏目

使用代码实现文字在超出内容时显示省略号

代码 实现 使用 显示 内容 文字 超出 省略号
2023-06-13 09:11:15 时间

一行超出显示省略

overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
<html>
   <div class="box-42b6">演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字</div>
</html>
<style>
    .box-42b6{
        border: 1px solid #999;
        width: 200px;

        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
</style>

:::

两行(多行)超出显示省略号

overflow: hidden;
white-space: normal;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;

显示的行数由line-clamp样式的值决定。

<html>
   <div class="box2-42b6">演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字演示文字</div>
</html>
<style>
    .box2-42b6{
        border: 1px solid #999;
        width: 200px;

        overflow: hidden;
        white-space: normal;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;

      }
</style>

:::

JS判断是否显示了省略号

有时候我们需要知道是否已经溢出,显示了省略号,可以用到clientHeightscrollHeight的知识:

let cHeight = noWrapDiv.clientHeight;
let sHeight = noWrapDiv.scrollHeight;
if (sHeight > cHeight) {
      console.log("已经溢出显示省略号");
} else {
      console.log("没有溢出");
}

这里可以用于判断是否溢出显示展开收缩按钮。

知识点拓展

scrollHeight:元素内容的高度,包括由于溢出导致的视图中不可见内容。不包含滚动条、边框和外边距。

clientHeight:元素内容的可视区的高度,包含内边距,但不包括水平滚动条、边框和外边距。

offsetHeight:元素的像素高度,高度包含该元素的垂直内边距和边框,且是一个整数。