Установите максимальное количество символов в базе textarea по высоте и ширине Textarea - PullRequest
2 голосов
/ 19 июня 2020

Примечания: Я попробовал все вопросы и ответы, связанные с этим топом c.

Я хочу ограничить количество символов в зависимости от высоты и ширины Textarea. . Предположим, я установил Textarea height :50px и width:60px;, поэтому я хочу предотвратить символ после завершения Textarea.

Примечания: Установить максимальное количество символов по Textarea height и width.

Связанные поисковые ссылки

  1. limit-height-of-textarea-based-on-content
  2. ограничение-символов текстового поля

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

Ответы [ 2 ]

0 голосов
/ 19 июня 2020

Вы можете установить свойство height и width как единицу измерения ch (символ). И установите атрибут maxlength="(width) * (height / line-height)" на textarea.

.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>
0 голосов
/ 19 июня 2020

Я создал код, смотрящий на то, сколько символов помещается в ширину и высоту текстового поля, и установил максимальную длину текстового поля на основе этого числа

$('.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>
...