动态调整 HTML 文本输入宽度到内容 [英] Dynamically Adjust HTML Text Input Width to Content

查看:22
本文介绍了动态调整 HTML 文本输入宽度到内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于这个我找不到明确的答案,如果我错过了,请原谅.

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.

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

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!

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:

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

span {
    display: inline-block;
}

p {
    font-family: arial;
}

小提琴

推荐答案

甚至使用 onkeypress

看这个例子: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>

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

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

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

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

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

并在 css 中提供 min-width

And in css provide min-width

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

编辑:

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

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

示例: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';
    }

});

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

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