使用Range API截断文本

时间:2018-03-17 17:57:44

标签: javascript html css truncate

我有一个带有文本的div,我想截断它,之后只剩下一个可以适合的文本。代码如下。在互联网上我只找到了一个插件,这取决于JQuery,但我知道,它可以用Range,如果有人有经验,请告诉我,这是怎么做的。

.container {
  height: 60px;
  border: 1px solid black;
}
<div class="container">
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
</div>

2 个答案:

答案 0 :(得分:2)

您可以使用以下内容:

&#13;
&#13;
const container = document.querySelector('.container');
let lines = container.querySelectorAll('.text');

const bottomLine = container.getBoundingClientRect().bottom;
for (let line of lines) {
  if (line.getBoundingClientRect().bottom > bottomLine) {
    container.removeChild(line);
  }
}
&#13;
.container {
  height: 60px;
  border: 1px solid black;
}
&#13;
<div class="container">
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

  

看看

&#13;
&#13;
<div class="container">
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
  <div class="text">Lorem lorem lorem lorem lorem</div>
</div>
&#13;
{{1}}
&#13;
&#13;
&#13;

  

说明:您可以制作容器

  1. 可滚动:使用overflow:auto;
  2. 不可滚动:只需使用overflow:hidden
  3. 隐藏其余内容