这是一个 MERN 堆栈应用程序。我尝试使用 this script 使文本区域的高度响应内容.
看起来外部 javascript 文件正在工作,因为我尝试将 alert
放入 for 循环并且它确实有效。所以我尝试将警报放在 OnInput()
函数中,但未调用 alert
。因此,我认为这个功能有问题。
index.html
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<script src="/main.js"></script>
</body>
main.js
var tx = document.getElementsByClassName('comment-area-responsive');
for (var i = 0; i < tx.length + 1; i++) {
// alert(i);
tx[i].setAttribute(
'style',
'height:' + tx[i].scrollHeight + 'px;overflow-y:hidden;'
);
tx[i].addEventListener('change', OnInput, false);
}
function OnInput() {
this.style.height = 'auto';
alert('hi2');
this.style.height = this.scrollHeight + 'px';
}
页面
<textarea
className='comment-area-responsive'
name='title'
placeholder='What do you think?'
value={text} onChange={e => setText(e.target.value)}
required
/>
最佳答案
从您的代码中删除了一些问题后,该脚本按预期工作 -
代替
change
事件,你应该听文本区域的input
事件。textarea
是一个容器,因此您使用结束标记关闭它</textarea>
而不是自闭标签。 Read more也许您正在使用其他一些库,因此请确保您确实需要
value={text}
和onChange={e => setText(e.target.value)}
textarea 上的属性。如果您只是为了这个脚本的目的而添加它们,那么就不需要它们,正如您在下面的代码中看到的那样。
在解决上述所有问题后,运行下面的代码片段以检查它是否正常工作
var tx = document.getElementsByClassName('comment-area-responsive');
for (var i = 0; i < tx.length; i++) {
tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
tx[i].addEventListener("input", OnInput, false);
}
function OnInput() {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
}
<div>
<textarea
class='comment-area-responsive'
name='title'
placeholder='What do you think?'
required
></textarea>
</div>
更新:让它与 React 一起工作,因为 React 处理 onChange
和 onInput
以同样的方式,你可以在你的onChange
中做到这一点处理程序,例如 -
const setText = (val) => {
this.setState({text: val});
var tx = document.getElementsByClassName('comment-area-responsive');
for (var i = 0; i < tx.length; i++) {
tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
}
}
...
<textarea
className='comment-area-responsive'
name='title'
placeholder='What do you think?'
value={text} onChange={e => setText(e.target.value)}
required>
</textarea>
关于javascript - 如何使输入字段的高度响应内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58008393/