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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:51:21  来源:igfitidea点击:

Measuring length of string in pixel in javascript

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 measureTextfunction :

最简单的解决方案是创建一个内存画布(即未添加到 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());
});

check jsfiddle

检查 jsfiddle