Javascript 动态调整 HTML 文本输入宽度到内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30520858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:19:21  来源:igfitidea点击:

Dynamically Adjust HTML Text Input Width to Content

javascriptjqueryhtmlformsinput

提问by ObbyOss

I can't quite find a clear answer on this, and excuse me if there is one I've missed.

对此我无法找到明确的答案,如果我错过了一个,请原谅。

I want my text input widths to automatically adjust to the size of the content within them. First with placeholder text than the actual text someone inputs.

我希望我的文本输入宽度自动调整到其中的内容大小。首先使用占位符文本而不是某人输入的实际文本。

I've created the below as an example. Currently, the boxes are far bigger than my placeholder text, causing huge amounts of white space, and it's obviously the same thing when I type in something.

我创建了以下示例。目前,这些框比我的占位符文本大得多,导致大量空白,当我输入内容时,这显然是一样的。

I've tried width auto, some jQuery, and twine and bubble gum I found on the internet. But nothing has worked yet. Any thoughts? Thanks!

我试过宽度自动,一些jQuery,以及我在互联网上找到的麻线和泡泡糖。但还没有奏效。有什么想法吗?谢谢!

HTML:

HTML:

<span><p>Hello, my name is </p></span>

<span><input type="text" id="input" class="form" placeholder="name"></span>

<span><p>. I am </p></span>

<span><input type="text" id="input" class="form" placeholder="age"></span>

    <span><p> years old.</p></span>

CSS:

CSS:

.form {
    border: 0;
    text-align: center;
    outline: none;
}

span {
    display: inline-block;
}

p {
    font-family: arial;
}

Fiddle

小提琴

采纳答案by Keval Bhatt

Use onkeypress even

甚至使用 onkeypress

see this example :http://jsfiddle.net/kevalbhatt18/yug04jau/7/

看这个例子:http : //jsfiddle.net/kevalbhatt18/yug04jau/7/

<input id="txt" placeholder="name" class="form" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"></span>
<input id="txt" placeholder="name" class="form" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"></span>

And for placeholderon load use jquery and apply placeholder size in to input

对于加载时的占位符使用 jquery 并将占位符大小应用到输入中

$('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px');
$('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px');

Even you can use idinstead of input this is just an example so that I used $(input)

即使你可以使用id而不是 input 这只是一个例子,所以我使用了$(input)

And in css provide min-width

并在 css 中提供 min-width

.form {
    border: 1px solid black;
    text-align: center;
    outline: none;
    min-width:4px;
}
.form {
    border: 1px solid black;
    text-align: center;
    outline: none;
    min-width:4px;
}



EDIT:

编辑



If you remove all text from input box then it will take placeholder value using focusout

如果您从输入框中删除所有文本,那么它将使用focusout取占位符值

Example: http://jsfiddle.net/kevalbhatt18/yug04jau/8/

示例http: //jsfiddle.net/kevalbhatt18/yug04jau/8/

$("input").focusout(function(){

    if(this.value.length>0){
        this.style.width = ((this.value.length + 1) * 8) + 'px';
    }else{
      this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';
    }

});
$("input").focusout(function(){

    if(this.value.length>0){
        this.style.width = ((this.value.length + 1) * 8) + 'px';
    }else{
      this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';
    }

});

回答by sudo rm -rf slash

One possible way:

一种可能的方式:

[contenteditable=true]:empty:before {
  content: attr(placeholder);
  color:gray;
}
/* found this online --- it prevents the user from being able to make a (visible) newline */
[contenteditable=true] br{
  display:none;
}
<p>Hello, my name is <span id="name" contenteditable="true" placeholder="name"></span>. I am <span id="age" contenteditable="true" placeholder="age"></span> years old.</p>

Source for CSS: http://codepen.io/flesler/pen/AEIFc.

CSS 来源:http: //codepen.io/flesler/pen/AEIFc

You'll have to do some trickery to pick up the values if you need the values for a form.

如果您需要表单的值,您将不得不做一些技巧来获取值。

回答by pradeep

Try with 'size' attribute. This will work even when you clear the text . Need jQuery to work this

尝试使用“ size”属性。即使您清除文本,这也将起作用。需要 jQuery 来解决这个问题

<div>
    <input id="txt" type="text" style="max-width: 100%;" placeholder="name">
</div>
<script>
    $(document).ready(function() {
        var placeholderLen = $('#txt').attr('placeholder').length;
        // keep some default lenght
        placeholderLen = Math.max(5, placeholderLen);
        $('#txt').attr('size', placeholderLen);

        $('#txt').keydown(function() {
            var size = $(this).val().length;
            $(this).attr('size', Math.max(placeholderLen, size));
        });
    });
</script>

回答by Vlad

input.addEventListener('input', () => input.style.width = input.scrollWidth);

Unfortunately this will only increase the size of the input. If you delete characters the size will not decrease. For some use cases this is perfectly fine.

不幸的是,这只会增加输入的大小。如果删除字符,则大小不会减小。对于某些用例,这完全没问题。

回答by Vlad

Kevin F is right, there is no native way to do it.

凯文 F 是对的,没有本地方法可以做到这一点。

Here is a one way to do it if you really want it to happen.

如果您真的希望它发生,这是一种方法。

In the code, there is an invisible span where the text is placed. Then we retrieve the width of the span.

在代码中,放置文本的位置有一个不可见的跨度。然后我们检索跨度的宽度。

https://jsfiddle.net/r02ma1n0/1/

https://jsfiddle.net/r02ma1n0/1/

var testdiv = $("#testdiv");
$("input").keydown( function(){
    var ME = $(this);
    //Manual Way
    //var px = 6.5;
    //var txtlength = ME.val().length;
    //$(this).css({width: txtlength * px });

   testdiv.html( ME.val() + "--");
   var txtlength = testdiv.width();
   ME.css({width: txtlength  }); 
});