问题
I'm looking for a solution to a problem, but I'm not able to find it. It could be in AngularJS or in Javascript (then I'll translate it in AngularJS). The problem is that I have to limit the rows of a simple textarea. The attribute 'rows=x' of HTML5 limit just the view. I have to limit the lines. The problem is that even if graphycally the lines go down, the components looks at it as a unique line. The user has to press ENTER to create a new line. But, I have to limit the lines. I did this directive:
angular.module('app').directive('maxlines', function (): any {
return function (scope: any, element: any, attrs: any) {
element.bind("keydown keypress", function (event: any) {
if (event.which === 13) {
var text = element.val(),
numberOfLines = (text.match(/\n/g) || []).length + 1,
maxRows = parseInt(element.attr('rows'));
if (event.which === 13 && numberOfLines === maxRows) {
return false;
}
}
});
};
});
It works if I press ENTER, but it doesnt work if I continue to write withouth press enter.
回答1:
I think you can do this with pure HTML.
<textarea cols="20" rows="5" wrap="hard" maxlength="100">
The wrap="hard"
means that once the user has reached the end of the line - in this case, 20 characters - a newline will be inserted.
Once the user has reached 100 characters - the same as filling in 5 lines with 20 characters - no more input will be allowed.
Now, this doesn't stop someone from adding 10 lines with 10 characters - but does it get close to what you want to do?
回答2:
This worked for me:
#your-textarea {
max-height: 5rem;
min-height: 2rem;
}
The user should be able to resize within that threshold.
来源:https://stackoverflow.com/questions/54035412/limit-rows-in-html5-textarea