优化文本呈现的性能?

时间:2017-07-13 00:44:43

标签: javascript html css

我说<p>内有一个<div>标记,其中包含以下属性:

div {
   height: 100px;
   width: 100px;
   overflow: hidden;
}

当页面加载时,我想继续向<p>标记添加单词,直到我检测到溢出,就像在第一个单词未添加时停止一样。

我使用以下代码执行此操作:

var textToRender = "People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.";
var words = textToRender.split(" ");

var div = document.getElementById("mydiv");
var p = document.getElementById("myp");

var i = 0;
while (p.clientHeight <= div.clientHeight && i<words.length) {
  p.textContent += words[i++] + ' ';
};
div {
  height: 55px;
  width: 200px;
  overflow: hidden;
}
<div id="mydiv">
  <p id="myp"></p>
</div>

现在说我用更大的div在更大规模上做这件事。更进一步说,我需要为不同文本的50个不同大小的div做这个。显然,即使在我们看来,这似乎是瞬间发生的,实际上每个词都必须逐一绘制。

我想弄清楚如何优化这种操作,假设我不知道行高,容器div高度或单词数。我的问题是:如果我在容器的顶部放置一个不透明的<div>以覆盖这个逐个字的图形,然后在函数检测到溢出时将其删除,这会提高性能,因为实际的单词不会是否会在while循环的每次迭代中被绘制?

如果没有,是否有任何类似的策略可以用来优化这种操作?

1 个答案:

答案 0 :(得分:0)

尝试二分搜索。这就是你想要的。

var textToRender = "People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.";
var words = textToRender.split(" ");

var div = document.getElementById("mydiv");
var p = document.getElementById("myp");

var l = 0, r = words.length, m;
while (l < r) {
  m = Math.floor((l + r) / 2);
  p.textContent = words.slice(0, m).join(' ');
  if (p.clientHeight <= div.clientHeight /* maybe you need add an additional line height here */) l = m + 1; else r = m - 1;
}
p.textContent = words.slice(0, l + 1).join(' ');
div {
  height: 55px;
  width: 200px;
  overflow: hidden;
}
<div id="mydiv">
  <p id="myp"></p>
</div>