fe-interview
fe-interview copied to clipboard
[js] 第336天 如何判断一个元素文本是否换行?
通过计算内容宽度,算出容器宽度,来比较宽度是否超过容器
计算总宽度和字体宽度,通过字数判断更合适!
获取 font-size 计算字符可能宽度,然后和元素宽度比较。 新建临时的 dom 加入文字并获取宽度,再与元素宽度比较。
前者能比较好处理 letter-spacing 之类的情况,但其实觉得两种方案都不太行。
- 文本元素是否有/n/t或
<br />
- white-space的取值
- 计算盒子的宽,计算所有文字的宽,比较两者
- 超过长度隐藏显示省略号的CSS
width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
这道题是判断换行吧,哪最简单的方案,clone一份包裹文本的dom,把高度设置为auto, 计算(包裹文字dom的clientHeight-内边距)/ line-height > 1 应该就换行了。当然这是简述方案,实际操作,可能还有些其他需要修正的偏差值计算。
突然又想到一个,这个应该是稳了。
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);
突然又想到一个,这个应该是稳了。
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
这样页面上会不会跳动呀