Appearance

「代码块」文本溢出

WXL570CN2021/06/02code-block文本溢出

「代码块」文本溢出

CSS实现

单行文本溢出隐藏

<p class='ell'>
  网易公司(NASDAQ:NTES),1997年由创始人兼CEO丁磊先生在广州创办,2000年在美国NASDAQ股票交易所挂牌上市,是中国领先的互联网技术公司。在开发互联网应用、服务及其它技术方面,始终保持中国业界领先地位。
</p>
/* 单行文字溢出虚点显 示*/
.ell{text-overflow:ellipsis; white-space:nowrap; overflow:hidden;}

多行文本溢出隐藏

使用:checked切换文本溢出

  <div class="bruce flex-ct-x">
    <div class="multiline-text line-5">
      <input class="multiline-text-checkbox" id="btn" type="checkbox" hidden />
      <p class="multiline-text-wrapper">
        <label
          for="btn"
          class="multiline-text-button"
          data-true="展开"
          data-false="收起"
        ></label>
        网易公司(NASDAQ:
        NTES),1997年由创始人兼CEO丁磊先生在广州创办,2000年在美国NASDAQ股票交易所挂牌上市,是中国领先的互联网技术公司。在开发互联网应用、服务及其它技术方面,始终保持中国业界领先地位。
      </p>
    </div>
  </div>
@mixin text-overflow($font-size: 20px, $line-ratio: 1.5) {
  $line-height: $font-size * $line-ratio;
  $btn-top: calc(100% - #{$line-height});
  $default-height: calc(#{$line-height} * 3);
  display: flex;
  overflow: hidden;
  margin: 50px;
  padding: 20px;
  border-radius: 5px;
  width: 100%;
  max-width: 1000px;
  box-shadow: 20px 20px 50px rgba(#000, 0.5);
  &-wrapper {
    overflow: hidden;
    position: relative;
    max-height: $default-height;
    line-height: $line-height;
    text-align: justify;
    font-size: $font-size;
    transition: all 500ms;
    &::before {
      float: right;
      height: $btn-top;
      content: "";
    }
    &::after {
      position: absolute;
      width: 100%;
      height: 100%;
      background-color: #fff;
      content: "";
    }
    @for $i from 1 through 5 {
      &.line-#{$i} {
        max-height: calc(#{$line-height} * #{$i});
      }
    }
  }
  &-checkbox:checked + .multiline-text-wrapper {
    max-height: 1000px;
    &::after {
      visibility: hidden;
    }
    .multiline-text-button {
      &::before {
        visibility: hidden;
      }
      &::after {
        content: attr(data-false);
      }
    }
  }
  &-button {
    float: right;
    clear: both;
    position: relative;
    margin-left: 30px;
    padding: 0 10px;
    border-radius: 5px;
    height: $line-height;
    background-color: #f66;
    cursor: pointer;
    font-size: $font-size;
    color: #fff;
    &::before {
      position: absolute;
      right: 100%;
      margin-right: 13px;
      color: #000;
      content: "...";
    }
    &::after {
      content: attr(data-true);
    }
  }
}

.multiline-text {
  @include text-overflow(20px);
}

JavaScript实现

const p = document.querySelector('p')
let words = p.innerHTML.split(/(?<=[\u4e00-\u9fa5])|(?<=\w*?\b)/g)
while (p.scrollHeight > p.clientHeight) {
  words.pop()
  p.innerHTML = words.join('') + '...'
}
Last Updated 2023-04-03 09:05:56