内容被截断时更改字体大小

问题描述 投票:0回答:1

我有一个 div 可以包含很长的文本(但并非总是如此)。 要求是将文本限制为三行并用省略号截断。 我已经弄清楚这部分了。

第二个要求是当文本被截断时,我需要减小字体大小,例如到 16px(尺寸是在需求中指定的,而不仅仅是“更小的东西”)。

div {
  font-size: 20px;
  max-width: 200px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}
<div>
  This is really long text that should
  definitely wrap for three lines and
  then terminate in an ellipsis if it's
  still too long, which it definitely is.
  It also needs to be a smaller font size.
</div>
<hr/>
<div>
  This text isn't long enough so it
  should be bigger.
</div>

是否可以检测文本何时被截断? 如果需要的话我愿意使用 JS。

基于宽度的解决方案(如 thisthis)对我不起作用,因为它们仅适用于单行文本。 我需要一些适用于多行截断文本的东西。

html css multiline truncate ellipsis
1个回答
0
投票

如果您愿意使用 javascript,那么下面的代码应该可以满足您的需求。它检查文本是否溢出,然后向其添加一个类。在本例中,该类只有 16px 字体大小,但实际上可以具有您想要的任何样式。

function adjustFontSizeForTruncatedText() {
  const elements = document.querySelectorAll('.trunc-text');

  elements.forEach(element => {
    // check if text is overflowing
    if (element.scrollHeight > element.clientHeight) {
      element.classList.add('truncated'); // smaller font size
    } else {
      element.classList.remove('truncated'); // original font size
    }
  });
}

adjustFontSizeForTruncatedText();

// rerun when the window is resized
window.addEventListener('resize', adjustFontSizeForTruncatedText);
.trunc-text {
  font-size: 20px;
  max-width: 200px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: font-size 0.3s ease;
}

.truncated {
  font-size: 16px;
}
<div class="trunc-text">
  This is really long text that should definitely wrap for three lines and then terminate in an ellipsis if it's still too long, which it definitely is. It also needs to be a smaller font size.
</div>
<hr/>
<div class="trunc-text">
  This text isn't long enough so it should be bigger.
</div>

这是另一种类似的方法。你可以选择。

document.querySelectorAll('.trunc-text').forEach(element => {
  if (element.scrollHeight > element.clientHeight) {
    element.classList.add('truncated');
  }
});
.trunc-text {
  font-size: 20px;
  max-width: 200px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  transition: font-size 0.3s ease;
}

.truncated {
  font-size: 16px;
}
<div class="trunc-text">
  This is really long text that should definitely wrap for three lines and then terminate in an ellipsis if it's still too long, which it definitely is. It also needs to be a smaller font size.
</div>

<hr/>

<div class="trunc-text">
  This text isn't long enough so it should be bigger.
</div>

© www.soinside.com 2019 - 2024. All rights reserved.