多行文字text-overflow: ellipsis省略号失效问题
    		       		warning:
    		            这篇文章距离上次修改已过438天,其中的内容可能已经有所变动。
    		        
        		                
                text-overflow: ellipsis 主要用于单行文本的溢出显示省略号。如果你在多行文本上使用这个属性,它可能不会工作,因为 text-overflow: ellipsis 仅适用于一行文本的末尾。
对于多行文本溢出显示省略号的需求,可以使用其他方法。以下是一些可能的解决方案:
- CSS Line Clamp
CSS Line Clamp 是一个提议中的特性,可以指定元素显示的最大行数。然后,超出指定行数的文本会显示省略号。不过,这个特性目前并不是所有浏览器都支持。
.ellipsis-multiline {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* Number of lines */
  overflow: hidden;
  text-overflow: ellipsis;
}- 使用JavaScript
如果你需要在多行文本上显示省略号,并且需要兼容所有浏览器,你可能需要使用JavaScript来动态地截断文本并添加省略号。以下是一个简单的JavaScript函数,用于实现这个功能:
function clampText(element, maxLines) {
  const context = element.getBoundingClientRect();
  const style = getComputedStyle(element);
  const lineHeight = parseInt(style.lineHeight);
  const maxHeight = maxLines * lineHeight;
 
  element.innerHTML = element.textContent.slice(0, (function() {
    const text = 0;
    const tempEl = document.createElement('div');
    tempEl.style.font = style.font;
    tempEl.style.lineHeight = style.lineHeight;
    tempEl.style.height = '0px';
    tempEl.style.overflow = 'hidden';
    tempEl.textContent = element.textContent;
    document.body.appendChild(tempEl);
    let count = 0;
    while (tempEl.offsetHeight < maxHeight) {
      text += tempEl.textContent.length;
      count += 1;
      tempEl.textContent += '...';
    }
    document.body.removeChild(tempEl);
    return text - 3;
  })());
}
 
const multilineText = document.getElementById('multiline-text');
clampText(multilineText, 3); // 3 is the maximum number of lines在这个例子中,clampText 函数通过创建一个临时的DOM元素,动态地计算文本的高度,直到它超过了所需的最大行高。然后,函数截断文本,并在末尾添加省略号。
评论已关闭