提问者:小点点

在文本溢出时生成省略号


我正在寻找一种在文本中添加省略号的方法,当它超过一定数量的行。我不想使用一个插件,我从另一个答案中找到了一个纯JS代码。但是,省略号“……”应用于每一个元素,即使它没有通过数字的限制。

HTML:

<p class="product-title">This is my product title example</p>

CSS:

.product-title {
    line-height: 1.4rem;
    height: 2.8rem;
}

!!我添加了两倍于行高的高度,以使超过两行的文本溢出。如果我想要三条线,我放三倍的线高。

JS:

function dotify(element) {
    var limit = element.offsetTop + element.offsetHeight;
    var dots = document.createElement('span');
    if (element['data-inner'])
        element.innerHTML = element['data-inner'];
    else
        element['data-inner'] = element.innerHTML;
    dots.appendChild(document.createTextNode('...'));
    element.style.overflow = 'hidden';
    element.appendChild(dots);
    while (dots.offsetTop + dots.offsetHeight > limit) {
        dots.previousSibling.data = dots.previousSibling.data
            .replace(/\W*\w+\W*$/, '')
    }
}


jQuery(".product-title").each(function() {
    dotify(this);
});

使用“之前”和“之后”的示例进行编辑:

前:Lorem ipsum dolor sit amet,consectetur adipiscing elit,

sed do eiusmod tempor incidunt ut labore et dolore magna aliqua.

Ut enim ad minim veniam,quis nostrud exeritation ullamco

laboris nisi ut aliquip ea commodo insulat。

之后:Lorem ipsum dolor sit amet,consectetur adipiscing elit,

sed do eiusmod tempor incidunt ut labore et dolore magna aliqua...


共1个答案

匿名用户

我认为您可以先检查内容的高度,然后再应用

null

function dotify(element) {
  if (element.clientHeight >= element.scrollHeight) {
    return
  }
  var limit = element.offsetTop + element.offsetHeight;
  var dots = document.createElement('span');
  if (element['data-inner']) {
    element.innerHTML = element['data-inner'];
  } else {
    element['data-inner'] = element.innerHTML;
  }
  dots.appendChild(document.createTextNode('...'));
  element.style.overflow = 'hidden';
  element.appendChild(dots);
  while (dots.offsetTop + dots.offsetHeight > limit) {
    dots.previousSibling.data = dots.previousSibling.data.replace(/\W*\w+\W*$/, '')
  }
}


jQuery(".product-title").each(function() {
  dotify(this);
});
.product-title {
  line-height: 1.4rem;
  height: 2.9rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="x1" class="product-title">This is my product title example</p>
<p id="x2" class="product-title">This is my product title example This is my product title example This is my product title example This is my product title example</p>
<p id="x3" class="product-title">This is my product title example This is my product title example This is my product title example This is my product title example This is my product title example</p>
<p id="x4" class="product-title">This is my product title example This is my product title example This is my product title example This is my product title example This is my product title example This is my product title example This is my product title example This is my product title example</p>