你可以使用它们中的任何一个,这一切都很好
1)<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">
2)var inputEl = document.getElementById("theInput");
function getWidthOfInput() {
var tmp = document.createElement("span");
tmp.className = "input-element tmp-element";
tmp.innerHTML = inputEl.value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
document.body.appendChild(tmp);
var theWidth = tmp.scrollWidth;
document.body.removeChild(tmp);
return theWidth;
}
function adjustWidthOfInput() {
inputEl.style.width = getWidthOfInput() + "px";
}
adjustWidthOfInput();
inputEl.onkeyup = adjustWidthOfInput;
3) // HTML // jQuery
$(function(){
$('#input').keyup(function(){
$('<span id="width">').append( $(this).val() ).appendTo('body');
$(this).width( $('#width').width() + 2 );
$('#width').remove();
});
});