Amare's blog
  • 页面
  • CSS
xugaoyi
2020-02-23

文字在一行或多行时超出显示省略号

# 文字在一行或多行时超出显示省略号

# 一行超出显示省略

overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
1
2
3
<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>
1
2
3
4
5
6
7
8
9
10
11
12
13

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

overflow: hidden;
white-space: normal;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
1
2
3
4
5
6

显示的行数由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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# JS判断是否显示了省略号

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

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

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

# 知识点拓展

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

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

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

Last Updated: 2021/07/06, 15:45:03
最近更新
01
使用State Hook
04-06
02
使用Effect Hook
04-06
03
Hook规则
04-06
更多文章>
Theme by Vdoing | Copyright © 2021-2021 Amare | MIT License | 宁ICP备2021002173号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式