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