根据里面的文字更改文本框宽度

时间:2014-08-12 13:13:27

标签: javascript jquery html asp.net asp.net-mvc

我正在使用如下文本框,我希望文本框的宽度将根据文本内部的大小而定,那可能吗?

@Html.TextBoxFor(model => model.Name, new { disabled = "disabled"  })

3 个答案:

答案 0 :(得分:2)

您的问题的简单答案是(使用一些jquery):

<script>
$(document).ready(function () {
    $('.txt').css('width', (($('.txt').val().length)+1) * 7 + 'px');  //You can increase or decrease multiplication factor i.e '7' here as required.
});
</script>

@Html.TextBoxFor(model => model.Name, new { disabled = "disabled",@class="txt" })

DEMO链接: - http://jsfiddle.net/Lbaf8cek/5/

不适用于此问题,因为此处文本框已停用,但如果未禁用文本框,则调整文本框宽度的最简单方法是:

<input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';">

小提琴链接: - http://jsfiddle.net/kartikeya/1vnw7d44/

答案 1 :(得分:1)

这篇文章处理我认为的同一主题:Growing text box based on width of characters input

由于您正在使用mvc并且文本框已禁用进行修改,因此您可以尝试:

@Html.TextBoxFor(model => model.Name, new { disabled = "disabled", length = Model.Name.Length() })

很抱歉,如果我的语法错误,但我没有IDE。但您正在做的是将文本框长度设置为输入的字符数。这应该有效地将文本框设置为正确的长度。除非你在某处应用了一些css规则。

更新:

另一种方式(如下所示)是使用Javascript,这样您就可以根据输入动态地扩大或缩短文本框。但最好是,当它只显示名称时,你应该试试@ Html.DisplayFor(...)

答案 2 :(得分:1)

更新代码说明:

在这里,输入将始终与其字符一样长,无论您在运行脚本之前键入,删除还是给它一个值: DEMO

//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