2016-11-06 84 views
0

我正在尝试使输入的自动调整大小,例如当用户输入时,输入会自动调整以适合输入内的值,但是,似乎我无法做正确或工作。任何想法,请帮助吗?调整对应于输入值长度的输入的宽度

$(document).ready(function(){ 
 
    $('input').on('input',function(){ 
 
    $(this).css('width',$(this).width()+$(this).val().length); 
 
    }); 
 
});
input{border:1px solid red;width:30px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 

 
<input type="text">

+0

您当前的代码肯定是改变输入的宽度,但我把它它不改变它,你会怎么样?也许告诉我们你是怎么想的? –

+0

我想使输入的宽度自动根据用户输入进行调整,输入的宽度应对应于输入的值长度,以便输入的值适合输入,就像当输入的值不会在该值包含一个长字符串。 –

回答

-1

如果你的目标是为它是一样宽必要的,也许有30像素缓冲区,那么问题是你每次添加的宽度,而不是重新从头开始重新计算它。如果你知道角色可能有多宽,这也会有所帮助,因此最好专门设置字体大小,或者甚至使用另一个隐藏元素来测量渲染文本的宽度。这里我用一个span为:

$(document).ready(function(){ 
 
    $('input').on('input',function(){ 
 
    var $this = $(this); 
 
    // Get the value 
 
    var val = $this.val(); 
 
    
 
    // Put it in the hidden span using the same font information 
 
    var $hidden = $(".hidden"); 
 
    $hidden.text(val); 
 
    
 
    // Set the input to the span's width plus a buffer 
 
    $this.css('width', $hidden.width() + 30); 
 
    }); 
 
});
input { 
 
    border:1px solid red; 
 
    font-size: 14px; 
 
    width:30px; 
 
} 
 
.hidden { 
 
    font-size: 14px; 
 
    display: none; 
 
}
<input type="text"> 
 
<span class="hidden"></span> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+1

...这将是“没有用”,究竟是怎样的? –

2

我建议在这种情况下使用contenteditable-span,我希望它能帮助。

#test{border:1px solid red;width:30px;}
<span id="test" contenteditable>I'm trying to make an auto resize like input</span>

+1

我喜欢这个想法。 –

+0

我喜欢这个想法,但根据我的要求,我更喜欢输入而不是跨度。 –