javascript 在javascript中以像素为单位测量字符串的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16478836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Measuring length of string in pixel in javascript
提问by KK123
How do I find the length of string in pixels in javascript , if I know the font-size and font-family?
如果我知道字体大小和字体系列,如何在 javascript 中以像素为单位找到字符串的长度?
回答by Denys Séguret
The simplest solution is to create an in memory canvas (i.e. one that isn't added to the DOM) and then use the measureText
function :
最简单的解决方案是创建一个内存画布(即未添加到 DOM 的画布),然后使用该measureText
函数:
var canvas = document.createElement('canvas');
var ctx = canvas.getContext("2d");
ctx.font = "11px Arial";
var width = ctx.measureText(str).width;
回答by Ganesh Bora
you can put your string into paragraph and use the jquery width function to get the width in pixel width
您可以将字符串放入段落并使用 jquery width 函数获取像素宽度的宽度
function showWidth(ele, w) {
$("div").text("The width for the " + ele +
" is " + w + "px.");
}
$("#getp").click(function () {
showWidth("paragraph", $("p").width());
});