fe-interview icon indicating copy to clipboard operation
fe-interview copied to clipboard

[js] 第336天 如何判断一个元素文本是否换行?

Open haizhilin2013 opened this issue 4 years ago • 6 comments

第336天 如何判断一个元素文本是否换行?

作者:zhutou1280

我也要出题

haizhilin2013 avatar Mar 16 '20 21:03 haizhilin2013

通过计算内容宽度,算出容器宽度,来比较宽度是否超过容器

计算总宽度和字体宽度,通过字数判断更合适!

webVueBlog avatar Mar 17 '20 03:03 webVueBlog

获取 font-size 计算字符可能宽度,然后和元素宽度比较。 新建临时的 dom 加入文字并获取宽度,再与元素宽度比较。

前者能比较好处理 letter-spacing 之类的情况,但其实觉得两种方案都不太行。

forever-z-133 avatar Mar 17 '20 09:03 forever-z-133

  • 文本元素是否有/n/t或<br />
  • white-space的取值
  • 计算盒子的宽,计算所有文字的宽,比较两者
  • 超过长度隐藏显示省略号的CSS
    width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    

longhui520 avatar Mar 17 '20 12:03 longhui520

这道题是判断换行吧,哪最简单的方案,clone一份包裹文本的dom,把高度设置为auto, 计算(包裹文字dom的clientHeight-内边距)/ line-height > 1 应该就换行了。当然这是简述方案,实际操作,可能还有些其他需要修正的偏差值计算。

pacez avatar Mar 20 '20 00:03 pacez

突然又想到一个,这个应该是稳了。

var target = document.querySelector('.wrap');
var orgStyle = target.getAttribute('style');
// 获取当前元素的 line-height 值
var lineHeight = window.getComputedStyle(target).lineHeight;
// 如果是 normal 就换为 px 值
if (lineHeight === 'normal') {
  var temp = document.createElement('div');
  temp.innerText = "字";
  document.body.appendChild(temp);
  lineHeight = temp.offsetHeight + 'px';
  document.body.removeChild(temp);
}
// 让元素高度等于其 line-height 高度
target.style.height = lineHeight;
// 然后便可判断出内容是否超出其容器,即是否已换行
if (target.offsetHeight < target.scrollHeight) {
  console.log('该元素里的文本换行了');
} else console.log('没换行');
orgStyle && target.setAttribute('style', orgStyle);

forever-z-133 avatar Mar 20 '20 13:03 forever-z-133

突然又想到一个,这个应该是稳了。

var target = document.querySelector('.wrap');
var orgStyle = target.getAttribute('style');
// 获取当前元素的 line-height 值
var lineHeight = window.getComputedStyle(target).lineHeight;
// 如果是 normal 就换为 px 值
if (lineHeight === 'normal') {
  var temp = document.createElement('div');
  temp.innerText = "字";
  document.body.appendChild(temp);
  lineHeight = temp.offsetHeight + 'px';
  document.body.removeChild(temp);
}
// 让元素高度等于其 line-height 高度
target.style.height = lineHeight;
// 然后便可判断出内容是否超出其容器,即是否已换行
if (target.offsetHeight < target.scrollHeight) {
  console.log('该元素里的文本换行了');
} else console.log('没换行');
orgStyle && target.setAttribute('style', orgStyle);

mark

xiaoqiangz avatar Sep 19 '22 08:09 xiaoqiangz

这样页面上会不会跳动呀

erhulee avatar Jun 04 '24 03:06 erhulee