如何计算输入HTML元素的宽度,以使其与其内容的大小匹配? [英] How to calculate the width of an input HTML element so that it matches the size of its content?

查看:289
本文介绍了如何计算输入HTML元素的宽度,以使其与其内容的大小匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算输入HTML元素的宽度,以使其与其内容的大小相匹配?
我已经在用户键入时立即更新输入:

 < input type ='text'onkeydown ='this.size = this.value.length'/> 

然而,这似乎不完全正确,因为它没有考虑到一些字符




  • 如果我只输入一些l字符,我会得到越来越多的空格。

  • 如果我只输入一些w字符,则大小将不足


  • $ b

    PS:为什么我想这样做(已经回答这个问题的答案已删除)?
    我有句子,我必须用输入替换括号内容(例如:[user]是[years] old)。我不知道这个句子可以是什么,所以我不知道一个足够的长度的输入,我想保持它的可读性在一行(避免太多的空格)。

    measureText()方法来获取字符串的宽度。



    编辑



    查找够快


    How to calculate the width of an input HTML element so that it matches the size of its content ? I already update an input on the fly as the user types :

    <input type='text' onkeydown='this.size=this.value.length' />
    

    However, this does not seem completely correct because it does not take into account the fact that some characters are longer than others :

    • I will get more and more whitespace if I type only some "l" characters
    • the size will be insufficient if I type only some "w" characters

    How to proceed?

    PS: Why I want to do this (already answered this in a answer that was deleted)? I have sentences in which I have to replace the bracket content by inputs (ex: [user] is [years] old). I have no idea what the sentence can be, so I do not know an adequate length for the inputs, and I would like to keep it readable on one line (avoiding too much whitespace).

    解决方案

    You could use a (hidden) canvas and the measureText() method of the context to get your string's width.

    EDIT:

    Looks fast enough.

    这篇关于如何计算输入HTML元素的宽度,以使其与其内容的大小匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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