我在<p>
中有一个<div>
标记,我在其中设置了以下属性:
div {
height: 105px;
width: 60px;
overflow: hidden;
}
如果<p>
标记包含大量文本,则其中一些文本将被截断。
我的目标是检测未显示的第一个单词是什么。
例如,在以下场景中:
div {
height: 105px;
width: 60px;
overflow: hidden;
}
<div>
<p>People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.</p>
</div>
该函数将返回单词“explode”。
我从this question知道,检测是否有溢出很容易,但是我们可以更进一步检测哪个词是第一个隐藏的吗?
答案 0 :(得分:4)
经过多种方法后,我认为最简单的方法是逐个添加一个词,然后检查段落是否溢出:
window.onload=function(){
var el=document.getElementById("el");
var words=el.textContent.split(" ");
el.textContent="";
var thatword=words.find(function(word,i){
el.textContent+=(i?" ":"")+word;
//console.log(el.clientWidth,el.scrollWidth,el.clientHeight,el.scrollHeight);
return el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight;
});
alert(thatword);
};
#el {
height: 105px;
width: 60px;
overflow: hidden;
}
<div>
<p id="el">People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.</p>
</div>
这实际上可能会改善渲染速度,因为所有溢出的内容永远不会再次添加。