【发布时间】:2021-06-17 13:02:11
【问题描述】:
我正在尝试设置一个简单的表单,其特点是如果用户输入的文本比textarea 宽,它将自动调整大小。需要明确的是,我希望拥有与 contenteditable="true" 属性相同的行为 span 标记。
<form action="/form" method="POST" style="margin-top: 100px;">
<p>
My name is <textarea name="name" cols="10" rows="1" placeholder="enter name"></textarea> and I come from a village called <textarea name="village" cols="10" rows="1" placeholder="enter village"></textarea>
. Everybody from the village of <textarea cols="10" rows="1" placeholder="enter village"></textarea> knows that my name is <textarea cols="10" rows="1" placeholder="enter name"></textarea>
</p>
<p>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I found a very similar question for the height of a textarea 所以我只是尝试让 js 代码适应宽度。不幸的是,它确实适用于高度(见图)但不适用于宽度。我错过了什么?
<script>
const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
tx[i].setAttribute("style", "width:" + (tx[i].scrollWidth) + "px;overflow-x:hidden;");
tx[i].addEventListener("input", OnInput, false);
}
function OnInput() {
this.style.width = "auto";
this.style.width = (this.scrollWidth) + "px";
}
</script>
【问题讨论】:
-
在 span 标签中实际使用
contenteditable="true"是否有问题?如果您需要在表单中发布该数据,您可以收听input事件并更新隐藏的输入或在提交时将其复制。 -
我尝试过 enter village 但我没有得到变量,所以我认为跨度标签在表单中是不可能的,这就是我尝试使用 textarea 元素的原因.你能告诉我如何使用它们吗?我认为这可能是我的问题的答案。
标签: javascript html css web