2016-03-03 73 views
2

我有一个文本框在我的HTML与白色底部边框聚焦时,我希望它改变宽度的文本字段的当前文本的长度(当然有一些限制)。我试过CSS最小宽度和最大宽度,但它似乎什么都不做。我认为用JS实现它需要一个硬编码的宽度表,我不想这样做。改变尺寸<input>

编辑:
这只是简单的CSS,但这里的代码:

#container { 
 
    width: 100%; 
 
    height: 52px; 
 
    background: #673ab7; 
 
} 
 

 
#textbox { 
 
    font-family: sans-serif; 
 
    font-size: 20px; 
 
    font-weight: bold; 
 
    color: white; 
 
    background: none; 
 
    border: none; 
 
    vertical-align: top; 
 
    margin-top: 13px; 
 
    margin-left: 13px; 
 
    outline: none; 
 
} 
 

 
#textbox:focus { 
 
    border-bottom: 2px solid white; 
 
}
<div id="container"> 
 
    <input type="text" id="textbox" placeholder="placeholder" /> 
 
</div>

+0

你的要价是有点不清楚什么。直到你开始输入,边框的宽度是输入的整个宽度吗?如果你想边界改变_as某人types_那么你将需要使用JS。 – hungerstar

+0

@ hungerstar对不起,我的意思是文本框的宽度... – NieDzejkob

回答

0

我找到了一种方法,没有任何宽度硬编码后,我发现this。 我在这里使用jQuery是因为我已经在我的项目中使用了它,但它应该比较容易将它移植到普通的JavaScript。像&,<,>和空格这样的字符可能会出错,所以需要用&...;编码替换。

$(document).ready(function(){ 
 
    $('#textbox').on('input', function(){ 
 
    if($('#textbox').val().length == 0){ 
 
     $('#measure').html($('#textbox').attr('placeholder')); 
 
    }else{ 
 
     var text = $('#textbox').val(); 
 
     text = text.replace(/&/g, '&amp;'); 
 
     text = text.replace(/</g, '&lt;'); 
 
     text = text.replace(/>/g, '&gt;'); 
 
     text = text.replace(/ /g, '&nbsp;'); 
 
     $('#measure').html(text); 
 
    } 
 
    
 
    var w = $('#measure').width(); 
 
    if(w > 600) w = 600; 
 
    $('#textbox').width(w); 
 
    }); 
 
    
 
    $('#textbox').trigger('input'); 
 
});
html, body { 
 
    margin: 0; 
 
} 
 

 
#container { 
 
    width: 100%; 
 
    height: 52px; 
 
    background: #673ab7; 
 
} 
 

 
#textbox { 
 
    font-family: sans-serif; 
 
    font-size: 20px; 
 
    font-weight: bold; 
 
    color: white; 
 
    background: none; 
 
    border: none; 
 
    vertical-align: top; 
 
    margin-top: 13px; 
 
    margin-left: 13px; 
 
    outline: none; 
 
} 
 

 
#textbox:focus { 
 
    border-bottom: 2px solid white; 
 
} 
 

 
#measure { 
 
    position: absolute; 
 
    visibility: hidden; 
 
    height: auto; 
 
    width: auto; 
 
    white-space: nowrap; 
 
    font-size: 20px; 
 
    font-weight: bold; 
 
    font-family: sans-serif; 
 
    padding: 0; 
 
    margin: 0; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="container"> 
 
    <input type="text" id="textbox" placeholder="placeholder" /> 
 
</div> 
 

 
<div id="measure"></div>

1

这应该工作不够好:

<form> 
<input type="text" id="textfield" onkeyup="changeSize()"> 
</form> 

var sizeIs=20; 
function changeSize(){ 
sizeIs=sizeIs+5; 
document.getElementById("textfield").style.width= sizeIs+"px"; 
} 

这样做是什么,每次用户键入一个字符,函数f并且增加文本字段的大小。你可以用这个作为指导去做你需要的任何事情。

+0

谢谢,但使用硬编码5px宽度不是我想要的。另外,退格将增加宽度,而不是减小宽度。但是,多亏了你,我意识到我需要**来使用JS,当时我只是想用它作为最后的手段。 – NieDzejkob