根据其值更改文本框宽度

change textbox width based on it's value

我正在尝试根据文本框的值更改文本框的宽度,但它似乎不起作用。 这是我的 aspx:

<asp:TextBox ID="TxtbSizeOzel" runat="server" CssClass="text-center"></asp:TextBox>$

我为代码隐藏中的调整方法创建了一个 onKeyUp 事件:

TxtbSizeOzel.Attributes.Add("onKeyUp", "Expand(this)");

最后是我的 javascript 方法:

function Expand(obj)
 {
   if (!obj.savesize) obj.savesize = obj.size;
    obj.size = Math.max(obj.savesize, obj.value.length);
 }

我没有收到任何错误,但它就是不工作。

尝试使用 JQuery 的 .width() 属性。它支持 getset 操作,用于对 HTML 中的控件或元素进行宽度操作。

如果你想使用 JavaScript,你可以试试这个:

document.getElementById("yourControlId").style.width = "300px";

希望对您有所帮助。

更新了代码说明:

开始吧,无论您是在 运行 脚本之前键入、删除还是给它赋值,输入的长度始终与其字符一样长:Demo here

//this is a plugin snippet (or function) to check if the element has
//horizontal scrollbar
$.fn.hasHorizontalScrollBar = function() {
  if (this[0].clientWidth < this[0].scrollWidth) {
    return true
  } else {
    return false
  }
}
//the end of plugin

var originalWidth=$('.txt').width(); //we store the original width
//(the width of the input at the page load) in a variable to use it as a 
//measurement in order to not let the input get smaller than this size 

//this function checks the width of `.txt` (the input) to see if it has 
//horizontal scrollbar or not, if it does then expands the width of the input to
//the scroll size, else it checks to see if the width is added to the 
//original width, if so, removes one character (depending on the font size it'll
//change - here it is 7 px)
function changeWidth(){
    if($('.txt').hasHorizontalScrollBar()){
        $('.txt').width(document.getElementsByClassName('txt')[0].scrollWidth);
    }
    else if(originalWidth<$('.txt').width()){
        $('.txt').width($('.txt').width()-7);
    }
};
//end of the function

changeWidth(); //run the function at page load, to give the input a size as wide as its
// character's length

$('.txt').keydown(changeWidth); //assign the function to the keydown event of the input
//so whenever a character is added or removed the function will run again