输入时获取输入文本宽度 [英] Get input text width when typing

查看:71
本文介绍了输入时获取输入文本宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有输入类型文字

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

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

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

这就是我的尝试:

document.getElementById("txtid").offsetWidth;

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

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

These two does not give the width of the text entered

基本上我想要的是:

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

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.

推荐答案

我看到两种方式。



第一次

您可以使用内容可编辑而不是输入的div。像这样你可以看到div的宽度。

You can use a div with content editable instead input. Like this you can see the width of the div.

var elemDiv = document.getElementById('a');

elemDiv.onblur = function() {
  console.log(elemDiv.clientWidth + 'px');
}

div {
  width: auto;
  display: inline-block;
}

<div id='a' contenteditable="true">Test</div>

注意:像@Leon Adler所说,这种方式允许从其他程序粘贴图像,表格和格式。因此,您可能需要使用javascript进行一些验证,以便在获得尺寸之前检查内容。

Note : Like @Leon Adler say, this 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.

第二

使用输入类型文本并将内容转换为不可见的div。你可以看到不可见div的宽度。

Use an input type text and past the content into an invisible div. And you can see the width of the invisible 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>

注意:为此,您必须拥有相同字体字体大小输入 div 标签。

Note : For this way, you must have the same font and font size on input and div tags.

这篇关于输入时获取输入文本宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆