如何测量文本在Javascript中占用的空间? [英] How can you measure the space that a text will take in Javascript?

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

问题描述

在Javascript中,我有一个特定的字符串,我想以某种方式测量在某个元素内需要多少空间(以像素为单位)。

In Javascript, I have a certain string, and I would like to somehow measure how much space (in pixels) it will take within a certain element.

基本上我有一个元素,将漂浮在一切以外(像一个工具提示),我需要手动通过Javascript设置它的宽度,所以它会调整到内部的文本。

我不能自动增长自然就像一个内联元素将水平生长以包含其子元素。

Basically what I have is an element that will float above everything else (like a tooltip), and I need to set its width manually through Javascript, so it will adjust to the text inside.
I can't have it "auto-grow" naturally like an inline element would grow horizontally to contain its children.

在Windows中有API可以做到这一点。有什么方法可以在Javascript中做同样的事情吗?

如果没有正确的方法,你相信什么方法是可行的?
(喜欢,尝试不同的宽度和检查高度,以确保它没有超过一定的阈值)。

In Windows there are APIs that do this. Is there a way to do the same thing in Javascript?
If there is no decent way, what approach do you believe is feasible? (Like, trying out different widths and checking the height to make sure it didn't go over a certain threshold).

像素值我可以硬编码在我的JS更好,显然。

The less "pixel values" I can hardcode in my JS the better, obviously.

推荐答案

试试这个

http:// blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/

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

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