在文本区域(如<textarea>
元素)上设置最小和最大行数可以通过CSS和JavaScript来实现。下面是一个完整的解决方案,包括HTML、CSS和JavaScript代码示例。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Textarea Min and Max Rows</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<form>
<label for="textArea">Enter text:</label>
<textarea id="textArea" rows="5"></textarea>
</form>
<script src="script.js"></script>
</body>
</html>
textarea {
width: 300px;
padding: 10px;
margin: 10px 0;
resize: vertical; /* Allow vertical resizing */
}
document.addEventListener('DOMContentLoaded', function() {
const textArea = document.getElementById('textArea');
const minHeight = 5; // Minimum number of rows
const maxHeight = 10; // Maximum number of rows
textArea.addEventListener('input', function() {
const lineHeight = parseInt(getComputedStyle(textArea).lineHeight);
const newHeight = Math.min(Math.max(textArea.scrollHeight, minHeight * lineHeight), maxHeight * lineHeight);
textArea.style.height = `${newHeight}px`;
});
});
<textarea>
元素,并为其设置一个ID以便在JavaScript中引用。<textarea>
的样式,包括宽度、内边距和允许垂直调整大小。<textarea>
元素。minHeight
和maxHeight
)。input
事件监听器,当用户输入文本时,计算并设置<textarea>
的高度。scrollHeight
属性获取文本的实际高度,并根据最小和最大行数调整高度。这种设置在需要限制用户输入长度或格式的表单中非常有用,例如评论框、留言板或搜索建议框。
通过这种方式,你可以有效地控制<textarea>
的最小和最大行数,确保用户输入的内容在指定的范围内。
领取专属 10元无门槛券
手把手带您无忧上云