当键入超过最大宽度时,动态扩展文本区域的高度

Dynamically expand the height of a textarea when typing more then the max width

本文关键字:扩展 动态 文本 区域 高度      更新时间:2023-09-26

当键入超过文本区域元素的最大宽度时,如何水平增大文本区域?我也不想看到水平滚动条。

呈现的网页

<textarea name="CatchPhrase" class="input-validation-error" id="CatchPhrase" aria-invalid="true" aria-required="true" aria-describedby="CatchPhrase-error" rows="2" cols="20" data-val-required="The Catch Phrase field is required." data-val="true" data-val-maxlength-max="50"
data-val-maxlength="The field Catch Phrase must be a string or array type with a maximum length of '50'." htmlattributes="{ id = profileCatchPhrase, class = form-control }">I like yoga sd;lasdlk asdks';aksd'asd 'asd';las ';asd'lasd';las'dl as'dla'sdl'asld as'd;las'dl; a;sdlka;sdklasd ;alsd;lkasda ;alskd;lkasd ;lkasd;lk</textarea>

呈现 HTML 之前

<div class="form-group">
  @Html.LabelFor(model => model.CatchPhrase, htmlAttributes: new { @class = "control-label col-lg-2 col-md-2 col-sm-2 col-xs-2" })
  <div class="col-lg-10 col-md-10 col-sm-10 col-xs-10">
    @Html.TextAreaFor(model => model.CatchPhrase, new { htmlAttributes = new { id = "profileCatchPhrase", @class = "form-control" } }) @Html.ValidationMessageFor(model => model.CatchPhrase, "", new { @class = "text-danger" })
  </div>
</div>

尝试这样的事情:

$('#CatchPhrase').on('input', function() {
  $(this).outerHeight(38).outerHeight(this.scrollHeight);
});

参见:https://stackoverflow.com/a/34513436/4613398

jsfiddle:

https://jsfiddle.net/3qmztmjj/

如果我

正确理解了您的问题并且您想增加文本区域的水平宽度,您可以使用maxlength检查文本字符并使用步骤来增加宽度。希望这个片段对你有帮助。

$("#profileCatchPhrase").keypress(function() {
    if ($(this).val().length > $(this).attr("data-val-maxlength-max")) {
      var width = parseInt($(this).css("width").split("p")[0]) + 10;
      $(this).css("width", width + "px");
      $(this).attr("data-val-maxlength-max", parseInt($(this).attr("data-val-maxlength-max")) + 5);
    }
  });

在此,我使用了10px作为icreament步骤,您可以相应地调整它。

好吧,我假设您想水平扩展文本区域而不是垂直扩展文本区域,那么您可以尝试这样的事情:

<textarea type="text" value="" placeholder="Autosize"></textarea>

并编写一个简单的JavaScript函数,该函数将水平扩展:

$('textarea').keyup(function () {
 // I'm assuming that 1 letter will expand the input by 10 pixels
 var oneLetterWidth = 10;
 // I'm also assuming that input will resize when at least eleven characters
 // are typed
 var minCharacters = 11;
 var len = $(this).val().length;
 if (len > minCharacters) {
     // increase width
     $(this).width(len * oneLetterWidth);
 } else {
     // restore minimal width;
     $(this).width(150);
 }
});

您还可以设置文本区域最大宽度,因为它应该在一段时间后停止扩展,因此只需将此 css 包含在 html 的 head 部分中:

 textarea { 
 max-width: 400px;
 }

使用jquery和textarea的id,如下所示

$(function() {
   $('#CatchPhrase').autogrow();
});