Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/427.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript计算文本宽度_Javascript_Textbox - Fatal编程技术网

使用JavaScript计算文本宽度

使用JavaScript计算文本宽度,javascript,textbox,Javascript,Textbox,我想使用JavaScript来计算字符串的宽度。这是否可能不必使用单空格字体 如果不是内置的,我唯一的想法就是为每个字符创建一个宽度表,但这是非常不合理的,尤其是支持不同的类型大小(以及所有浏览器)。在JavaScript中,设置要测量的字体大小和属性,将字符串放入DIV中,然后读取DIV的当前宽度和高度。它将拉伸以适合内容,并且大小将在字符串呈现大小的几个像素范围内 var fontSize=12; var测试=document.getElementById(“测试”); test.styl

我想使用JavaScript来计算字符串的宽度。这是否可能不必使用单空格字体


如果不是内置的,我唯一的想法就是为每个字符创建一个宽度表,但这是非常不合理的,尤其是支持不同的类型大小(以及所有浏览器)。在JavaScript中,设置要测量的字体大小和属性,将字符串放入DIV中,然后读取DIV的当前宽度和高度。它将拉伸以适合内容,并且大小将在字符串呈现大小的几个像素范围内

var fontSize=12;
var测试=document.getElementById(“测试”);
test.style.fontSize=fontSize;
变量高度=(test.clientHeight+1)+“px”;
变量宽度=(test.clientWidth+1)+“px”
控制台。原木(高度、宽度)
#测试
{
位置:绝对位置;
可见性:隐藏;
高度:自动;
宽度:自动;
空白:nowrap;/*感谢Herb Caudill的评论*/
}

abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvxyz
文本
var textWidth=document.getElementById(“text”).offsetWidth;
只要标记没有应用其他样式,这就应该可以工作。 offsetWidth将包括任何边框的宽度、水平填充、垂直滚动条宽度等。

有一个名为Ext.util.TextMetrics的类,该类“为文本块提供精确的像素测量,以便您可以准确确定给定文本块的高度和宽度(以像素为单位)”。您可以直接使用它,也可以查看它的源代码,以了解如何做到这一点

jQuery:

(function($) {

 $.textMetrics = function(el) {

  var h = 0, w = 0;

  var div = document.createElement('div');
  document.body.appendChild(div);
  $(div).css({
   position: 'absolute',
   left: -1000,
   top: -1000,
   display: 'none'
  });

  $(div).html($(el).html());
  var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
  $(styles).each(function() {
   var s = this.toString();
   $(div).css(s, $(el).css(s));
  });

  h = $(div).outerHeight();
  w = $(div).outerWidth();

  $(div).remove();

  var ret = {
   height: h,
   width: w
  };

  return ret;
 }

})(jQuery);
下面的代码剪断“计算”span标记的宽度,如果它太长,则在其后面附加“…”,并减少文本长度,直到它适合其父级(或直到它尝试了一千多次)

CSS

HTML


这是我的房子
我的房子就是你的房子
这个地名肯定太宽了,放不下
JavaScript(带jQuery)

//循环分类为“places”的元素,并检查其子元素“span”是否太长而无法容纳
$(“.places”)。每个(功能(索引,项目){
var obj=$(项目).find(“span”);
if(目标长度){
var placename=$(obj.text();
if($(obj).width()>$(item).width()&&placename.trim().length>0){
var限值=0;
做{
极限++;
placename=placename.substring(0,placename.length-1);
$(obj).文本(地名+“…”);
}while($(obj).width()>$(item).width()&&limit<1000)
}
}
});
这对我很有用

// Handy JavaScript to measure the size taken to render the supplied text;
// you can supply additional style information too if you have it.

function measureText(pText, pFontSize, pStyle) {
    var lDiv = document.createElement('div');

    document.body.appendChild(lDiv);

    if (pStyle != null) {
        lDiv.style = pStyle;
    }
    lDiv.style.fontSize = "" + pFontSize + "px";
    lDiv.style.position = "absolute";
    lDiv.style.left = -1000;
    lDiv.style.top = -1000;

    lDiv.innerHTML = pText;

    var lResult = {
        width: lDiv.clientWidth,
        height: lDiv.clientHeight
    };

    document.body.removeChild(lDiv);
    lDiv = null;

    return lResult;
}

这是一个我没有举例说明的例子。看起来我们都在同一页上

String.prototype.width = function(font) {
  var f = font || '12px arial',
      o = $('<div></div>')
            .text(this)
            .css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
            .appendTo($('body')),
      w = o.width();

  o.remove();

  return w;
}
String.prototype.width=函数(字体){
var f=font | |“12px arial”,
o=$('')
.文本(本)
.css({'position':'absolute','float':'left','white space':'nowrap','visibility':'hidden','font':f})
.appendTo($(“body”),
w=o.宽度();
o、 删除();
返回w;
}
使用它很简单:
“一个字符串”.width()


**添加了
空白:nowrap
以便可以计算宽度大于窗口宽度的字符串。

您可以使用画布,这样就不必处理太多css属性:

var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "20pt Arial";  // This can be set programmaticly from the element's font-style if desired
var textWidth = ctx.measureText($("#myElement").text()).width;
请尝试以下代码:

function GetTextRectToPixels(obj)
{
var tmpRect = obj.getBoundingClientRect();
obj.style.width = "auto"; 
obj.style.height = "auto"; 
var Ret = obj.getBoundingClientRect(); 
obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px"; 
return Ret;
}

文本的宽度和高度可以通过
clientWidth
clientHeight

var element = document.getElementById ("mytext");

var width = element.clientWidth;
var height = element.clientHeight;
确保“样式位置”属性设置为“绝对”

element.style.position = "absolute";

不需要在
div
中,可以在
p
span
中。更好的方法是在显示元素之前检测文本是否适合。所以你可以使用这个函数,它不需要元素出现在屏幕上

function textWidth(text, fontProp) {
    var tag = document.createElement("div");
    tag.style.position = "absolute";
    tag.style.left = "-999em";
    tag.style.whiteSpace = "nowrap";
    tag.style.font = fontProp;
    tag.innerHTML = text;

    document.body.appendChild(tag);

    var result = tag.clientWidth;

    document.body.removeChild(tag);

    return result;
}
用法:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}
var size = calculateSize("Hello world!", {
   font: 'Arial',
   fontSize: '12px'
});

console.log(size.width); // 65
console.log(size.height); // 14

在HTML5中,您可以使用(进一步解释)

:

将此画布方法与的变体进行比较,以便可以分析和比较结果的准确性

这种方法有几个优点,包括:

  • 比其他(基于DOM的)方法更简洁、更安全,因为它不会更改全局状态,例如您的DOM
  • 可通过以下方式进行进一步定制,例如
    textAlign
    textbelineline
注意:将文本添加到DOM时,请记住还要考虑

注2:在某些浏览器上,此方法会产生亚像素精度(结果是一个浮点数),而在其他浏览器上则不会(结果只是一个int)。您可能希望对结果运行
Math.floor
(或
Math.ceil
),以避免不一致。由于基于DOM的方法从来都不是亚像素精度的,因此该方法比这里的其他方法具有更高的精度


根据(感谢评论中的贡献者),如果在基于DOM的方法中添加了缓存,并且您没有使用Firefox,那么Canvas方法和基于DOM的方法的速度差不多相同。在Firefox中,由于某种原因,这种画布方法比基于DOM的方法快得多(截至2014年9月)。

我为此编写了一个小工具。也许它对某人有用。它在没有jQuery的情况下工作

用法:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}
var size = calculateSize("Hello world!", {
   font: 'Arial',
   fontSize: '12px'
});

console.log(size.width); // 65
console.log(size.height); // 14

小提琴手:

我想这与德帕克的作品很相似,但它是基于路易斯·拉扎里斯在《纽约时报》上发表的一篇文章

(函数($){
$.fn.autofit=函数(){
var hiddenDiv=$(document.createElement('div'),
内容=空;
css('display','none');
$('body').append(hiddenDiv);
$(this).bind('fit keyup keydown blur update focus',函数(){
content=$(this.val();
内容=内容。替换(/\n/g,
if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}
var textWidth = (function (el) {
    el.style.position = 'absolute';
    el.style.top = '-1000px';
    document.body.appendChild(el);

    return function (text) {
        el.innerHTML = text;
        return el.clientWidth;
    };
})(document.createElement('div'));
/**
 * Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
 * 
 * @param {String} text The text to be rendered.
 * @param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
 * 
 * @see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
function getTextWidth(text, font) {
    // re-use canvas object for better performance
    var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
}

console.log(getTextWidth("hello there!", "bold 12pt arial"));  // close to 86
var size = calculateSize("Hello world!", {
   font: 'Arial',
   fontSize: '12px'
});

console.log(size.width); // 65
console.log(size.height); // 14
(function($){

        $.fn.autofit = function() {             

            var hiddenDiv = $(document.createElement('div')),
            content = null;

            hiddenDiv.css('display','none');

            $('body').append(hiddenDiv);

            $(this).bind('fit keyup keydown blur update focus',function () {
                content = $(this).val();

                content = content.replace(/\n/g, '<br>');
                hiddenDiv.html(content);

                $(this).css('width', hiddenDiv.width());

            });

            return this;

        };
    })(jQuery);
String.prototype.width = function (fontSize) {
    var el,
        f = fontSize + " px arial" || '12px arial';
    el = document.createElement('div');
    el.style.position = 'absolute';
    el.style.float = "left";
    el.style.whiteSpace = 'nowrap';
    el.style.visibility = 'hidden';
    el.style.font = f;
    el.innerHTML = this;
    el = document.body.appendChild(el);
    w = el.offsetWidth;
    el.parentNode.removeChild(el);
    return w;
}

// Usage
"MyString".width(12);
<h1 id="test1">
    How wide is this text?
</h1>
<div id="result1"></div>
<hr/>
<p id="test2">
    How wide is this text?
</p>
<div id="result2"></div>
<hr/>
<p id="test3">
    How wide is this text?<br/><br/>
    f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi  ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j
</p>
<div id="result3"></div>
function getTextWidth(text, font) {
    var canvas = getTextWidth.canvas ||
        (getTextWidth.canvas = document.createElement("canvas"));
    var context = canvas.getContext("2d");
    context.font = font;
    var metrics = context.measureText(text);
    return metrics.width;
};

$("#result1")
.text("answer: " +
    getTextWidth(
             $("#test1").text(),
             $("#test1").css("font")) + " px");

$("#result2")
    .text("answer: " +
        getTextWidth(
             $("#test2").text(),
             $("#test2").css("font")) + " px");

$("#result3")
    .text("answer: " +
        getTextWidth(
             $("#test3").text(),
             $("#test3").css("font")) + " px");
function measureText(str, fontSize = 10) {
  const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]
  const avg = 0.5279276315789471
  return str
    .split('')
    .map(c => c.charCodeAt(0) < widths.length ? widths[c.charCodeAt(0)] : avg)
    .reduce((cur, acc) => acc + cur) * fontSize
}
function getNodeTextWidth(nodeWithText) {
    var textNode = $(nodeWithText).contents().filter(function () {
        return this.nodeType == Node.TEXT_NODE;
    })[0];
    var range = document.createRange();
    range.selectNode(textNode);
    return range.getBoundingClientRect().width;
}
textMetrics.init(document.querySelector('h1'), { fontSize: '20px' });

textMetrics.init({
  fontSize: '14px',
  lineHeight: '20px',
  fontFamily: 'Helvetica, Arial, sans-serif',
  fontWeight: 400,
  width: 100,
});