简体   繁体   English

如何根据具有固定字符数但字体大小可能不同的输入来调整文本框宽度?

[英]How to adjust textbox width based on input that has fixed number of characters but font size may vary?

So I'm receiving a text from a server response :所以我收到了来自服务器响应的文本

"AC-8D-9A-7E" “AC-8D-9A-7E”

and the text has a fixed number of characters of 11 as above and I want to display it on a textbox in HTML.并且文本具有固定数量的11 个字符,我想将其显示在 HTML 的文本框中。

However, what I want is that, initially the textbox has a width of 0px and when I received the text from the server, I will then append it to the textbox where the width of the textbox is roughly equal to the width of the text :但是,我想要的是,最初文本框的宽度为 0px ,当我从服务器接收到文本时,我会将其append 到文本框宽度大致等于文本宽度的文本框

在此处输入图像描述

How do i set the width of the textbox so that it is roughly the width of the text ?如何设置文本框的宽度,使其大致是文本的宽度

 * { margin: 0; padding: 0; box-sizing: border-box; } html { height: 100%; font-size: 1vw; } body { height: 100%; } #container { display: flex; width: 100%; } #code { border-color: black; width: 0px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href = "style.css"> <title>Document</title> </head> <body> <div id = "container"> <input type = "text" id = "code" disabled> </div> <script> document.getElementById("code");value = "AC-8D-9A-7E"; </script> </body> </html>

If I comment out the #code segment css, the textbox will be looking like so:如果我注释掉#code 段 css,文本框将如下所示:

在此处输入图像描述

Therefore, how do i retrieve the rough width of the textbox so that it is roughly the same as the width of the text?因此,我如何检索文本框的粗略宽度,使其与文本的宽度大致相同?

Edit: I do not need to consider situations like paste or delete events mentioned in other post as the textbox for me just serve as a display purpose编辑:我不需要考虑其他帖子中提到的粘贴或删除事件等情况,因为我的文本框只是用作显示目的

You can use ch unit.您可以使用ch单位。 1ch is approximately equal to the width of 1 character. 1ch大约等于 1 个字符的宽度。 Since you know the length of the input value is going to be 11 characters, you can set the width of it to be 11ch .由于您知道输入值的长度将为 11 个字符,因此您可以将其宽度设置为11ch

So when you get the response from the server, you can set the width to be 11ch .因此,当您从服务器获得响应时,您可以将宽度设置为11ch Although you could make it 12ch and make it look a tad bit better (or you could add padding to the input)尽管您可以将其设置为12ch并使其看起来更好一些(或者您可以在输入中添加填充)

#code {
    width: 11ch;
}

The accepted answer to this question gives a great explanation of the difference between ch and em .这个问题的公认答案很好地解释了chem之间的区别。 Something you may want to consider.您可能需要考虑的事情。

Use the size attribute that specifies the width of input in characters.使用 size 属性指定输入字符的宽度。 I used 11 since your display results has 11 chars.我使用了 11,因为您的显示结果有 11 个字符。 Also, I recommend that you use some padding for input field.另外,我建议您对输入字段使用一些填充。

<input type="text" size="11" id="code" disabled />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM