输入时获取输入文本宽度

时间:2022-09-22 03:39:47

I have a input type text

我有一个输入类型的文本

<input type="text" id="txtid">

When i start typing text inside input, i should be able to get the lenght of the entered text.

当我开始在输入中键入文本时,我应该能够获得输入文本的长度。

This is what I tried:

这是我试过的:

document.getElementById("txtid").offsetWidth;

and

var test = document.getElementById("txtid");
var width = (test.clientWidth + 1) + "px";

These two does not give the width of the text entered

这两个不给出输入文本的宽度

Basically what I want is:

基本上我想要的是:

输入时获取输入文本宽度

For suppose input text width is 320px. I need the width of the entered text i.e 120px, which keeps on changing when I enter.

假设输入文本宽度为320px。我需要输入文本的宽度,即120px,当我进入时,它会不断变化。

4 个解决方案

#1


13  

I see two ways.

First:

第一:

You can use a div with content editable instead input. Like this you can see the width of the div. And you can push the text into an hidden input.

您可以使用内容可编辑而不是输入的div。像这样你可以看到div的宽度。您可以将文本推送到隐藏的输入中。

var elemDiv = document.getElementById('a'),
  elemInput = document.getElementById('b');

elemDiv.onblur = function() {
  elemInput.value = elemDiv.innerHTML;
  console.log(elemDiv.clientWidth + 'px');
}
div {
  width: auto;
  display: inline-block;
}
<div id='a' contenteditable="true">Test</div>
<input id='b' type='hidden'>

Second:

第二:

You can use the same logic, but reversal. Use an input type text and past the content into an invisible div.

您可以使用相同的逻辑,但可以反转。使用输入类型文本并将内容过去到不可见的div中。

var elemDiv = document.getElementById('a'),
  elemInput = document.getElementById('b');

elemInput.oninput = function() {
  elemDiv.innerText = elemInput.value;
  console.log(elemDiv.clientWidth + 'px');
}
.div {
  width: auto;
  display: inline-block;
  visibility: hidden;
  position: fixed;
  overflow:auto;
}
<input id='b' type='text'>
<div id='a' class='div'></div>


Note : For last way, you must have the same font and font size on input and div tags.
Note 2 : Like @Leon Adler say, the first way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.

注意:最后一种方法是,input和div标签上的字体和字体大小必须相同。注2:像@Leon Adler所说,第一种方法允许从其他程序粘贴图像,表格和格式。因此,在获取大小之前,您可能需要使用javascript进行一些验证来检查内容。

#2


9  

I have modified Chillers answer slightly, because it looks like you wanted the width rather than the letter count. I have created a span, which is absolute positioned off the screen. I am then adding the value of the input to it and then getting the width of the span. To make it more fancy you could create the span with javascript.

我已经修改了Chillers的回答,因为看起来你想要宽度而不是字母数。我创建了一个跨度,它绝对位于屏幕之外。然后我将输入的值添加到它,然后获得跨度的宽度。为了使它更加花哨,您可以使用javascript创建跨度。

Note that the input and the span would have to have the same CSS styling for this to be accurate.

请注意,输入和跨度必须具有相同的CSS样式才能准确。

document.getElementById("txtid").addEventListener("keyup", function(){
  var mrspan = document.getElementById("mrspan");
  mrspan.innerText = this.value;
  console.log(mrspan.offsetWidth + "px");
});
<input type="text" id="txtid">
<span id="mrspan" style="position:absolute;left:-100%;"></span>

#3


5  

UPDATE

UPDATE

Two things I want to put forward

我想提出两件事

  • Doing display none will not give you any offsetWidth if we are trying using vanilla JS. we can use visibility: hidden; or opacity:0 for that.

    如果我们尝试使用vanilla JS,那么执行display none将不会给你任何offsetWidth。我们可以使用visibility:hidden;或不透明度:0表示。

  • we need to add overflow:auto to the hidden span or else the text will be warped to the next line if it exceeds the browser window width and the width will stay fixed (width of window)

    我们需要添加overflow:auto到隐藏的span,否则如果超过浏览器窗口宽度,文本将被扭曲到下一行,宽度将保持固定(窗口的宽度)

OLD

You can try this approach

你可以尝试这种方法

Add a span and hide it

添加范围并隐藏它

<span id="value"></span>

and then onkeyup add the text of the textfield on your hidden span and get its width.

然后onkeyup在隐藏的跨度上添加文本字段的文本并获取其宽度。

WITH THE HELP OF JQUERY

借助观察者的帮助

SNIPPET (UPDATED)

SNIPPET(更新)

function update(elm,value) {
     $('#value').text(value);
     var width =   $('#value').width();
     $('#result').text('The width of '+ value +' is '+width +'px');
   
}
#value{
  display:none;
  overflow:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" oninput='update(this,this.value)'>
<span id="value"></span>
<div id="result"></div>

USING JS ONLY

仅使用JS

SNIPPET (UPDATED)

SNIPPET(更新)

function update(elm,value) {
     var span = document.getElementById('value');
     span.innerHTML = value;    
     var width = span.offsetWidth;
     document.getElementById('result').innerHTML = 'The width of '+ value +' is '+ width+ 'px';
   
}
#value{
  opacity:0;
  overflow:auto;
}
<input type="text" oninput='update(this,this.value)'>
<span id="value"></span>
<div id="result"></div>

#4


4  

Canvas measureText() method can be helpful in such a case. Call the following function whenever you need to get your text width:

Canvas measureText()方法在这种情况下可能会有所帮助。需要获取文本宽度时,请调用以下函数:

function measureMyInputText() {
    var input = document.getElementById("txtid");
    var c = document.createElement("canvas");
    var ctx = c.getContext("2d");
    var txtWidth = ctx.measureText(input.value).width;

    return txtWidth;
}

For more accurate result, you may set font styling to the canvas, especially if you set some font properties to the input. Use the following function to get the input font:

为了获得更准确的结果,您可以将字体样式设置为画布,尤其是在为输入设置某些字体属性时。使用以下函数获取输入字体:

 function font(element) {
     var prop = ["font-style", "font-variant", "font-weight", "font-size", "font-family"];
     var font = "";
     for (var x in prop)
         font += window.getComputedStyle(element, null).getPropertyValue(prop[x]) + " ";

     return font;
 }

Then, add this line to the frist function:

然后,将此行添加到frist函数:

ctx.font = font(input);

#1


13  

I see two ways.

First:

第一:

You can use a div with content editable instead input. Like this you can see the width of the div. And you can push the text into an hidden input.

您可以使用内容可编辑而不是输入的div。像这样你可以看到div的宽度。您可以将文本推送到隐藏的输入中。

var elemDiv = document.getElementById('a'),
  elemInput = document.getElementById('b');

elemDiv.onblur = function() {
  elemInput.value = elemDiv.innerHTML;
  console.log(elemDiv.clientWidth + 'px');
}
div {
  width: auto;
  display: inline-block;
}
<div id='a' contenteditable="true">Test</div>
<input id='b' type='hidden'>

Second:

第二:

You can use the same logic, but reversal. Use an input type text and past the content into an invisible div.

您可以使用相同的逻辑,但可以反转。使用输入类型文本并将内容过去到不可见的div中。

var elemDiv = document.getElementById('a'),
  elemInput = document.getElementById('b');

elemInput.oninput = function() {
  elemDiv.innerText = elemInput.value;
  console.log(elemDiv.clientWidth + 'px');
}
.div {
  width: auto;
  display: inline-block;
  visibility: hidden;
  position: fixed;
  overflow:auto;
}
<input id='b' type='text'>
<div id='a' class='div'></div>


Note : For last way, you must have the same font and font size on input and div tags.
Note 2 : Like @Leon Adler say, the first way allows pasting images, tables and formatting from other programs. So you maybe need some validation with javascript to check the content before get the size.

注意:最后一种方法是,input和div标签上的字体和字体大小必须相同。注2:像@Leon Adler所说,第一种方法允许从其他程序粘贴图像,表格和格式。因此,在获取大小之前,您可能需要使用javascript进行一些验证来检查内容。

#2


9  

I have modified Chillers answer slightly, because it looks like you wanted the width rather than the letter count. I have created a span, which is absolute positioned off the screen. I am then adding the value of the input to it and then getting the width of the span. To make it more fancy you could create the span with javascript.

我已经修改了Chillers的回答,因为看起来你想要宽度而不是字母数。我创建了一个跨度,它绝对位于屏幕之外。然后我将输入的值添加到它,然后获得跨度的宽度。为了使它更加花哨,您可以使用javascript创建跨度。

Note that the input and the span would have to have the same CSS styling for this to be accurate.

请注意,输入和跨度必须具有相同的CSS样式才能准确。

document.getElementById("txtid").addEventListener("keyup", function(){
  var mrspan = document.getElementById("mrspan");
  mrspan.innerText = this.value;
  console.log(mrspan.offsetWidth + "px");
});
<input type="text" id="txtid">
<span id="mrspan" style="position:absolute;left:-100%;"></span>

#3


5  

UPDATE

UPDATE

Two things I want to put forward

我想提出两件事

  • Doing display none will not give you any offsetWidth if we are trying using vanilla JS. we can use visibility: hidden; or opacity:0 for that.

    如果我们尝试使用vanilla JS,那么执行display none将不会给你任何offsetWidth。我们可以使用visibility:hidden;或不透明度:0表示。

  • we need to add overflow:auto to the hidden span or else the text will be warped to the next line if it exceeds the browser window width and the width will stay fixed (width of window)

    我们需要添加overflow:auto到隐藏的span,否则如果超过浏览器窗口宽度,文本将被扭曲到下一行,宽度将保持固定(窗口的宽度)

OLD

You can try this approach

你可以尝试这种方法

Add a span and hide it

添加范围并隐藏它

<span id="value"></span>

and then onkeyup add the text of the textfield on your hidden span and get its width.

然后onkeyup在隐藏的跨度上添加文本字段的文本并获取其宽度。

WITH THE HELP OF JQUERY

借助观察者的帮助

SNIPPET (UPDATED)

SNIPPET(更新)

function update(elm,value) {
     $('#value').text(value);
     var width =   $('#value').width();
     $('#result').text('The width of '+ value +' is '+width +'px');
   
}
#value{
  display:none;
  overflow:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" oninput='update(this,this.value)'>
<span id="value"></span>
<div id="result"></div>

USING JS ONLY

仅使用JS

SNIPPET (UPDATED)

SNIPPET(更新)

function update(elm,value) {
     var span = document.getElementById('value');
     span.innerHTML = value;    
     var width = span.offsetWidth;
     document.getElementById('result').innerHTML = 'The width of '+ value +' is '+ width+ 'px';
   
}
#value{
  opacity:0;
  overflow:auto;
}
<input type="text" oninput='update(this,this.value)'>
<span id="value"></span>
<div id="result"></div>

#4


4  

Canvas measureText() method can be helpful in such a case. Call the following function whenever you need to get your text width:

Canvas measureText()方法在这种情况下可能会有所帮助。需要获取文本宽度时,请调用以下函数:

function measureMyInputText() {
    var input = document.getElementById("txtid");
    var c = document.createElement("canvas");
    var ctx = c.getContext("2d");
    var txtWidth = ctx.measureText(input.value).width;

    return txtWidth;
}

For more accurate result, you may set font styling to the canvas, especially if you set some font properties to the input. Use the following function to get the input font:

为了获得更准确的结果,您可以将字体样式设置为画布,尤其是在为输入设置某些字体属性时。使用以下函数获取输入字体:

 function font(element) {
     var prop = ["font-style", "font-variant", "font-weight", "font-size", "font-family"];
     var font = "";
     for (var x in prop)
         font += window.getComputedStyle(element, null).getPropertyValue(prop[x]) + " ";

     return font;
 }

Then, add this line to the frist function:

然后,将此行添加到frist函数:

ctx.font = font(input);