在JavaScript中测量文本大小 [英] Measure text size in JavaScript

查看:96
本文介绍了在JavaScript中测量文本大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaScript中测量文字的大小。到目前为止这不是那么困难,因为我可以简单地把一个临时不可见的div到DOM树中,并检查offsetWidth和offsetHeight。问题是,我想在DOM准备好之前做这个。这是一个存根:

I want to measure the size of a text in JavaScript. So far this isn't so difficult because I can simply put a temporary invisible div into the DOM tree and check the offsetWidth and offsetHeight. The problem is, I want to do this BEFORE the DOM is ready. Here is a stub:

<html>
  <head>
    <script type="text/javascript">

    var text = "Hello world";
    var fontFamily = "Arial";
    var fontSize = 12;

    var size = measureText(text, fontSize, fontFamily);

    function measureText(text, fontSize, fontFamily)
    {
        // TODO Implement me!
    }      

    </script>
  </head>
  <body>
  </body>
</html>

再次:我知道当DOM(或body)发出准备好的信号时,如何异步地做。但我想要做的是同步的标题,如上面的存根所示。任何想法如何我可以完成这个?我现在的意见是,这是不可能的,但也许有人有一个疯狂的想法。

Again: I KNOW how to do it asynchronously when DOM (or body) signals that it is ready. But I want to do it synchronously right in the header as shown in the stub above. Any ideas how I can accomplish this? My current opinion is that this is impossible but maybe someone has a crazy idea.

推荐答案

你不必等到

将脚本移动到< body> 。现在 document.body 存在,因此您可以 document.body.insertBefore(myspan,document.body.firstChild)。 (但不要 appendChild ,否则你会把一个元素放在解析器的顶部,这通常会打破IE。)

Move the script to just inside <body>. Now document.body exists, so you can document.body.insertBefore(myspan, document.body.firstChild). (But don't appendChild, or you'll be putting an element on top of where the parser is, which will typically break IE.)

可能有更复杂的解决方法(可能使用canvas和 measureText())?但是这将是最简单的。

There may be more complicated workarounds (maybe using a canvas and measureText() for there?) but this is going to be by far the easiest.

这篇关于在JavaScript中测量文本大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆