我正在尝试根据文本框的值更改文本框的宽度,但它似乎不起作用。 这是我的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);
}
我没有收到任何错误,但它只是没有工作。
答案 0 :(得分:2)
更新代码说明:
在这里,输入将始终与其字符一样长,无论您在运行脚本之前键入,删除还是给它一个值: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
答案 1 :(得分:0)
尝试使用JQuery的.width()属性。它支持get
和set
操作,用于宽度操作HTML中的控件或元素。
如果你想使用JavaScript,你可以试试这个:
document.getElementById("yourControlId").style.width = "300px";
希望这有帮助。