提问者:小点点

根据文本区域的高度和宽度设置文本区域中的最大字符数


注意:我尝试了所有的问题&; 与此主题相关的答案。

我想根据文本区的高度和宽度限制字符数。 假设我已经设置了Textareaheight:50pxwidted:60px;,所以我希望在完成Textarea之后防止字符。

注意:按文本区域高度宽度设置最大字符数。

相关搜索链接

  1. 限制-基于内容的文本区域高度
  2. 文本区-字符限制

null

.textareaClass {
  height: 50px;
  width: 60px;
  resize: none;
  overflow: hidden
}
<textarea class="textareaClass"></textarea>

null


共2个答案

匿名用户

我创建了一个代码,查看文本区域的宽度和高度适合多少字符,并根据这个数字设置文本区域的最大长度

null

$('.textareaClass').keypress(function(){
	let width = $(this).css('width').replace(/[^-\d\.]/g, ''); //getting the width of textarea
  let height = $(this).css('height').replace(/[^-\d\.]/g, '');//getting the height of textarea
  let widthchar = Math.floor(parseInt(width) / 7.5);//based on the width howmuch characters fit sideways
  let heightchar = Math.floor(parseInt(height) / 15);//based on the height, howmuch lines of characters are there
  let totalchar = widthchar * heightchar; //multiply lines by chars sideways to get a total amount of chars
  $(this).attr('maxlength',totalchar);//setting the total as total for the text area
  $(".char").html('you are allowed to type:'+ totalchar+'character(s)');//output to see howmuch you can type, just for debug/programming reasons to see what's happening
});
.textareaClass {
  height:100px;
  width: 50px;
  resize: none;
  overflow: hidden
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="textareaClass"></textarea>
<div class="char">

</div>

匿名用户

可以将高度宽度属性设置为ch(字符)单位。 并将maxlength=“(width)*(height/line-height)”属性设置为textarea

null

.textareaClass {
  height: 10ch;
  width: 10ch;
  line-height: 2ch;
  resize: none;
  overflow: hidden
}
<!-- max-length should be 10 (width) * 10 (height) / 2 (line-height) = 10 * 5 = 50 -->
<textarea class="textareaClass" maxlength="50"></textarea>