请返回 jstextarea 自适应高度通过 js 改变 value 时也会被触发
以下是一个示例代码,可以实现 textarea 自适应高度,并且在改变 value 时也能触发:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Textarea 自适应高度</title>
<style>
/* 设置 textarea 样式 */
textarea {
width: 100%;
height: auto;
min-height: 50px;
font-size: 16px;
line-height: 1.4;
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
resize: none;
}
</style>
</head>
<body>
<textarea id="myTextarea"></textarea>
<script>
// 获取 textarea 元素
var textarea = document.getElementById('myTextarea');
// 设置 textarea 自适应高度
function setTextareaHeight() {
textarea.style.height = 'auto';
textarea.style.height = textarea.scrollHeight + 'px';
}
// 给 textarea 添加事件监听
textarea.addEventListener('input', function() {
setTextareaHeight();
});
// 改变 textarea 的 value 时也会触发自适应高度
textarea.value = '这是一段文本,可以改变 textarea 的 value。';
setTextareaHeight();
</script>
</body>
</html>
这段代码中,首先定义了一个 textarea 元素,并且添加了一些样式。然后通过 JavaScript 代码,定义了一个 setTextareaHeight 函数,该函数用于设置 textarea 的高度,使其自适应内容的高度。
接着,给 textarea 元素添加了一个 input 事件监听器,当用户输入内容时会触发该事件,从而调用 setTextareaHeight 函数进行高度调整。
最后,通过 JavaScript 代码改变了 textarea 的 value,并且调用了 setTextareaHeight 函数,从而触发了自适应高度。
原文地址: http://www.cveoy.top/t/topic/GDb 著作权归作者所有。请勿转载和采集!