开发者

How to calculate the length (in pixels) of a string in JavaScript?

开发者 https://www.devze.com 2023-02-18 04:29 出处:网络
How to calculate the length (in pixels) of a string in Ja开发者_Python百科vaScript?you can use simple code

How to calculate the length (in pixels) of a string in Ja开发者_Python百科vaScript?


you can use simple code

var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "11px Arial";        
var width = ctx.measureText(str).width;


Given the new information about your wanting to append an ellipsis for text overflow, I think the text-overflow CSS property is a better approach. See this article on quirksmode for more information: http://www.quirksmode.org/css/textoverflow.html


A working example of simshaun's suggestion: http://jsfiddle.net/tycjf/2/


The easiest way would be to write it into a span on the page, get the width, and then delete the span. Also, it's relative to whatever font-size the span inherits.

0

精彩评论

暂无评论...
验证码 换一张
取 消