繁体   English   中英

Textarea使用Jquery根据内容(使用表单控件类)调整大小

[英]Textarea adjust size based on content (with form-control class) using Jquery

大家好,

我想根据内容调整文本区域的大小,为此我尝试了类似的代码

<div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10"> 
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" onkeyup="textAreaAdjust(this)"></textarea>
      <br/>
    </div>
  </div>

并使用jQuery

 function textAreaAdjust(o) {
  o.style.height = "1px";
  o.style.height = (25+o.scrollHeight)+"px";
}

而我所面临的问题甚至是退格,对于任何新闻textarea的删除都在扩展得很长。它一直在工作,就像对于任何按键新闻textarea都会增加。如果我尝试不使用'class =“ form-control”工作正常。但是响应性不佳。请任何人帮助我摆脱这个问题。在此先感谢您。

在此处输入图片说明

使用jquery-elastic插件链接已死

在这里检查项目的分支Github Jquery-elastic

使用只需要一行代码即可。

$('#answer_sample').elastic();

参见JSFiddle

 /** * @name Elastic+ * @descripton grow and shrink your textareas automatically * * @author Casey W. Stark * @author-email casey@thestarkeffect.com * @author-website http://thestarkeffect.com * * @license MIT License - http://www.opensource.org/licenses/mit-license.php * * the original by: * @author Jan Jarfalk * @author-email jan.jarfalk@unwrongest.com * @author-website http://www.unwrongest.com */ (function($) { $.fn.elastic = function(options) { // We will create a div clone of the textarea // by copying these attributes from the textarea to the div. var mimics = [ 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'fontSize', 'lineHeight', 'fontFamily', 'width', 'fontWeight', 'textIndent' ]; // support multiple elements if (this.length > 1) { this.each(function() { // textareas only if (this.type != 'textarea') return false; $this.elastic() }); return this; } // cache the textarea jquery object var textarea = this; var twin = $('<div></div>').css({ 'position': 'absolute', 'display': 'none', 'word-wrap': 'break-word' }); var lineHeight = parseInt(textarea.css('line-height'), 10) || parseInt(textarea.css('font-size'), 10); var minHeight = parseInt(textarea.css('height'), 10) || lineHeight * 2; var maxHeight = parseInt(textarea.css('max-height'), 10) || Number.MAX_VALUE; var goalHeight = 0; var i = 0; // Opera returns max-height of -1 if not set if (maxHeight < 0) { maxHeight = Number.MAX_VALUE; } // Append the twin to the DOM // We are going to meassure the height of this, not the textarea. twin.appendTo(this.parent()); // Copy the essential styles (mimics) from the textarea to the twin var i = mimics.length; while (i--) { twin.css(mimics[i].toString(), textarea.css(mimics[i].toString())); } // Sets a given height and overflow state on the textarea function setHeightAndOverflow(height, overflow) { curratedHeight = Math.floor(parseInt(height, 10)); if (textarea.height() != curratedHeight) { textarea.css({ 'height': curratedHeight + 'px', 'overflow': overflow }); } } // This function will update the height of the textarea if necessary this.resize = function(options) { // need to update the lineheight if not set if (!lineHeight) { lineHeight = parseInt(textarea.css('line-height'), 10); } // set width to get proper height (width could change) twin.width(textarea.width()); // Get curated content from the textarea. var textareaContent = textarea.val().replace(/&/g, '&amp;').replace(/ /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\\n/g, '<br />'); var twinContent = twin.html(); if (textareaContent + '&nbsp;' != twinContent) { // Add an extra white space so new rows are added when you are at the end of a row. twin.html(textareaContent + '&nbsp;'); // Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height if (Math.abs(twin.height() - textarea.height()) > 3) { var goalHeight = twin.height(); if (goalHeight >= maxHeight) { setHeightAndOverflow(maxHeight, 'auto'); } else if (goalHeight <= minHeight) { setHeightAndOverflow(minHeight, 'hidden'); } else { setHeightAndOverflow(goalHeight, 'hidden'); } } } return textarea; }; // Hide scrollbars textarea.css({ 'overflow': 'hidden' }); // Update textarea size on keyup textarea.keyup(function() { textarea.resize(); }); // And this line is to catch the browser paste event textarea.on('input paste', function(e) { setTimeout(textarea.resize, 250); }); // Run resize once when elastic is initialized and return the textarea for chaining return this.resize(); }; })(jQuery); $('#answer_sample').elastic(); 
 @import url('http://getbootstrap.com/dist/css/bootstrap.css'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="form-group"> <div class="col-sm-10"> <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit Duis autem vel eum iriure dolor in hendrerit in vulputate velit es </textarea> <br/> </div> </div> 

您可以检测到密钥,如果它是退格键,则不执行任何操作,因此可以尝试此操作

$('#answer_sample').bind('keypress', function(e) {
   var code = e.keyCode || e.which;
   if(code != 8) { //Backspace keycode
     $(this).css('height', '1px');
     $(this).css('height', 25+o.scrollHeight)+'px');
   }

});

并从HTML中删除该功能

<div class="form-group">
    <label class="control-label col-sm-2" for="pwd">Sample Answer</label>
    <div class="col-sm-10"> 
     <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5" ></textarea>
      <br/>
    </div>
</div>

久经考验

 $(document).ready(function(){ $("#answer_sample").keyup(function(e) { while($(this).outerHeight() < this.scrollHeight + parseFloat($(this).css("borderTopWidth")) + parseFloat($(this).css("borderBottomWidth"))) { $(this).height($(this).height()+1); }; }); }); 
 <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="script.js"></script> </head> <body> <div class="form-group"> <label class="control-label col-sm-2" for="pwd">Sample Answer</label> <div class="col-sm-10"> <textarea class="form-control" name="answer_sample" id="answer_sample" rows="5"></textarea> <br/> </div> </div> </body> </html> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM