Javascript 基于它更改文本框宽度';s值

Javascript 基于它更改文本框宽度';s值,javascript,c#,asp.net,textbox,width,Javascript,C#,Asp.net,Textbox,Width,我试图根据textbox的值更改textbox的宽度,但它似乎不起作用。 这是我的aspx: <asp:TextBox ID="TxtbSizeOzel" runat="server" CssClass="text-center"></asp:TextBox>$ 最后是我的javascript方法: function Expand(obj) { if (!obj.savesize) obj.savesize = obj.size; obj.size =

我试图根据textbox的值更改textbox的宽度,但它似乎不起作用。 这是我的aspx:

<asp:TextBox ID="TxtbSizeOzel" runat="server" CssClass="text-center"></asp:TextBox>$
最后是我的javascript方法:

function Expand(obj)
 {
   if (!obj.savesize) obj.savesize = obj.size;
    obj.size = Math.max(obj.savesize, obj.value.length);
 }
我没有收到任何错误,但它就是不工作。

尝试使用JQuery的属性。它支持
get
set
操作,用于HTML中控件或元素的宽度操纵

如果您想使用JavaScript,可以尝试以下方法:

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

希望这有帮助。

更新了代码说明:

在这里,无论您在运行脚本之前键入、删除或为其指定值,输入的长度始终与字符的长度相同:

//这是一个插件片段(或函数),用于检查元素是否具有
//水平滚动条
$.fn.hasHorizontalScrollBar=函数(){
if(此[0].clientWidth<此[0].scrollWidth){
返回真值
}否则{
返回错误
}
}
//插件的结尾
var originalWidth=$('.txt').width()//我们存储原始宽度
//(页面加载时输入的宽度)输入一个变量,以将其用作
//测量以避免输入小于此大小
//此函数用于检查“.txt”(输入)的宽度,以查看是否有
//水平滚动条与否,如果有,则将输入的宽度扩展到
//滚动大小,否则它会检查宽度是否已添加到
//如果是原始宽度,则删除一个字符(取决于将使用的字体大小)
//变化-这里是7像素)
函数changeWidth(){
if($('.txt').hasHorizontalScrollBar()){
$('.txt').width(document.getElementsByClassName('txt')[0].scrollWidth);
}

否则如果(originalwidthtnx@Koray Durudogan)接受,我很乐意帮助您。您使用jquery吗?
document.getElementById("yourControlId").style.width = "300px";
//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