Javascript clientWidth:相同的代码,不同的结果

时间:2017-04-19 01:40:40

标签: javascript html css d3.js svg

我正在使用此问题的答案(Calculate text width with JavaScript),创建隐藏的div并计算字符串大小。然后,我创建一个svg rect,其宽度与字符串+10相同。

tipnode.append("rect")
  .attr("height", 25)
  .attr("x", function(d){return d.x*180+45 - getTextWidth(testsize(d.name))/2.0;})
  .attr("y", function(d) { return (d.y-1)*80+45; })
  .attr("width", function(d){return getTextWidth(testsize(d.name))+10;});

getTextWidth函数如下

 function getTextWidth(text) {
  var test = document.getElementById("Test");
  test.innerHTML = text;
  var width = test.clientWidth;
  return width;
  };

函数testsize只是调整大字符串的大小。

测试css:

#Test{
  font-family: 'Alegreya Sans SC', sans-serif;
  font-size: 10.5px;
  font-weight: bold;
  position: absolute;
  visibility: hidden;
  height: auto;
  width: auto;
  white-space: nowrap;
}

字体配置与rect上的文本相同。 Alegreya Sans SC是一种字体(https://fonts.google.com/specimen/Alegreya+Sans+SC)。

问题是:有时,当我加载页面时,rect会变大文本。然后,我改变了行#34; var width = test.clientWidth;" to" var width = test.clientHeight;",加载页面,放回原始代码,重新加载页面,rects宽度恰好适合!相同的代码得到了不同的结果!

请帮助,我不知道该怎么做:(

0 个答案:

没有答案