wolichuang / dailyInterview

面试、工作中遇到的issue
0 stars 0 forks source link

css-文字截断 #39

Open wolichuang opened 3 years ago

wolichuang commented 3 years ago

单行截断

nowrap 会将多个连续空格符或换行符视为一个空格符,默认情况下,文本超过容器宽度时,会自动在合适的地方添加换行符进行换行。设置了该值后,换行效果会被消除,使文本不进行换行,从而实现文本单行显示的效果。此时我们会发现文本发生了溢出:后面的文本内容跑到容器外面

.single {
    white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

多行截断:-webkit-line-clamp

-webkit-line-clamp 可以指定文本在第几行进行截断并添加 …。该属性只有在 display 属性设置成 -webkit-box 或者 -webkit-inline-box 并且 -webkit-box-orient 属性设置成 vertical时才有效果。

.multi-line {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
}

伪元素方法

伪元素 ::before(当然也可以使用 ::after) 务必要设置和容器元素一样的背景,否则会出现文字重叠的效果

.multi-line {
  position: relative;
  line-height: 20px;
  max-height: 60px;
  overflow: hidden;
  word-break: break-all;
}
.multi-line::before {
  content: "…";
  position: absolute;
  top: 40px;
  right: 0;
  background-color: #fff;
}

伪元素-背景图片

.fade-out{
  position: relative;
  line-height: 20px;
  max-height: 60px;
  overflow: hidden;
  word-break: break-all;
}
.fade-out::after {
  content: "";
  position: absolute;
  top: 40px;
  right: 0;
  width: 40%;
  height: 20px;
  background-image: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 70%);
}

文本超出容器时,显示 “查看更多” 按钮

.read-more {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3;
  overflow: hidden;
  word-break: break-all;
  max-width: 600px;
}

const content = document.querySelector('.read-more')
const btn = document.querySelector('button')
function setReadmoreVisible() {
  if (content.scrollHeight > content.clientHeight) {
    btn.style.display = 'inline-block'
  } else {
    btn.style.display = 'none'
  }
}

window.addEventListener('resize', function()  {
  setReadmoreVisible()
}, false)
window.onload = function() {
  setReadmoreVisible()
}