html+css+Jquery 实现 文本域 文字数量限制、根据输入字数自适应高度
    		       		warning:
    		            这篇文章距离上次修改已过443天,其中的内容可能已经有所变动。
    		        
        		                
                以下是实现文本域字数限制和高度自适应的示例代码:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Textarea Limit Example</title>
<style>
  #myTextarea {
    width: 300px;
    min-height: 50px;
    max-height: 200px;
    height: auto;
    overflow-y: hidden;
    resize: none;
  }
</style>
</head>
<body>
 
<textarea id="myTextarea" maxlength="250" placeholder="Enter text here..."></textarea>
<div id="charCount">0/250</div>
 
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
  var $textarea = $('#myTextarea');
  var $charCount = $('#charCount');
 
  $textarea.on('input', function() {
    var maxLength = $textarea.attr('maxlength');
    var currentLength = $textarea.val().length;
    var charCount = maxLength - currentLength;
 
    $charCount.text(currentLength + '/' + maxLength);
 
    // Auto-grow the textarea
    $textarea.css('height', 'auto').height($textarea[0].scrollHeight);
  }).trigger('input'); // Trigger the input event to initialize the textarea height
});
</script>
 
</body>
</html>CSS:
#myTextarea {
  width: 300px;
  min-height: 50px;
  max-height: 200px;
  height: auto;
  overflow-y: hidden;
  resize: none;
}jQuery:
$(document).ready(function() {
  var $textarea = $('#myTextarea');
  var $charCount = $('#charCount');
 
  $textarea.on('input', function() {
    var maxLength = $textarea.attr('maxlength');
    var currentLength = $textarea.val().length;
    var charCount = maxLength - currentLength;
 
    $charCount.text(currentLength + '/' + maxLength);
 
    // Auto-grow the textarea
    $textarea.css('height', 'auto').height($textarea[0].scrollHeight);
  }).trigger('input'); // Trigger the input event to initialize the textarea height
});这段代码实现了以下功能:
- 文本域 #myTextarea具有最大字符数限制(通过maxlength属性设置)。
- 在文本域下方有一个计数器 #charCount显示当前字数和最大字数。
- 通过jQuery监听 input事件以更新计数器和文本域的高度。
- 文本域高度会根据输入内容自动增长,直至达到 max-height。
- 使用了 .trigger('input')来在文档准备就绪时立即处理一次输入事件,以便正确设置初始高度。
评论已关闭