javascript - 根据其值更改文本框宽度

标签 javascript c# asp.net textbox width

我正在尝试根据文本框的值更改文本框的宽度,但它似乎不起作用。 这是我的 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);
 }

我没有收到任何错误,但它不起作用。

最佳答案

更新了代码说明:

在这里,输入将始终与其字符一样长,无论您在运行脚本之前键入、删除还是为其赋值: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

关于javascript - 根据其值更改文本框宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34130118/

相关文章:

javascript - 没有/低 alpha 的 Canvas PutImageData 颜色丢失

php - 移动到另一页时发出警报

c# - 动态创建强名称,无需 Sn.exe

c# - 在事件再次触发之前等待事件完成

asp.net - 两个 UpdatePanels 并行工作,一个不更新

asp.net - HtmlGenericControl ("br") 渲染两次

javascript - 使用javascript下载文件弹出框

javascript - jquery替换问题

javascript - 使用 JavaScript 进行运动检测和简单分析?

c# - Task.Run() 是否与创建 Task 实例然后 Start() 相同?