切换同位置两个textarea时第二个出现缩进问题求助
解决textarea显示时的缩进问题
问题出在textarea会原样保留标签内部的空白字符(换行、空格都算)。看你的HTML代码,area2的<textarea>标签拆成了两行,第二行的name="area2"是缩进后写的,这就导致内容"Some text here"前面被带上了缩进的空格,显示时自然就有缩进了。
给你两个解决办法:
方法一:调整HTML结构(推荐)
把textarea的内容和标签的结束尖括号放在同一行,彻底消除多余空白:
<td><textarea readonly id="area2" cols="80" rows="6" hidden name="area2">Some text here</textarea></td>
核心是让<textarea>的>和内容、内容和`之间没有任何换行或多余空格。
方法二:用JS清除内容空白
如果不想改HTML格式,就在显示area2的时候,用代码去掉内容前后的空白:
document.getElementById('subject').addEventListener('change', function () { const area1 = document.getElementById('area1'); const area2 = document.getElementById('area2'); if (this.value === 'Subject1') { area1.style.display = 'none'; area2.style.display = 'block'; // 清除内容前后的空白字符 area2.value = area2.value.trim(); } else { area1.style.display = 'block'; area2.style.display = 'none'; } });
另外提一句:你同时用了hidden属性和JS控制display,其实可以统一用hidden属性来切换,逻辑更清晰:
// 显示area2时 area1.hidden = true; area2.hidden = false; // 显示area1时 area1.hidden = false; area2.hidden = true;
内容的提问来源于stack exchange,提问作者j.t.2.4.6
相关产品推荐
相关产品推荐

