css html:检测溢出并更改字体大小

46scxncf  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(123)

我搜索解决方案,以检测溢出的css-class .entry.title,并在检测时采取一些css,以减少字体大小。
示例:检测前的CSS:

.entry-title {
font-size: 1.42em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}

检测后的CSS:

.entry-title {
font-size: calc(1.42em * 0.95);
white-space: inherit;
overflow: inherit;
text-overflow: inherit;
}

我认为这可以用javascript来完成,但我没有经验。

ddhy6vgd

ddhy6vgd1#

下面是一个JavaScript解决方案,用于检测.entry-title类中的溢出并减小字体大小:

const entryTitle = document.querySelector('.entry-title');

if (entryTitle.offsetWidth < entryTitle.scrollWidth) {
  
  entryTitle.style.fontSize = 'calc(1.42em * 0.95)';
  
  entryTitle.style.whiteSpace = 'inherit';
  entryTitle.style.overflow = 'inherit';
  entryTitle.style.textOverflow = 'inherit';
}

此代码使用querySelector方法选择.entry-title元素,并使用offsetWidth和scrollWidth属性确定是否存在溢出。如果存在溢出,则将字体大小减小5%,并删除空白、溢出和文本溢出属性。

相关问题