为什么wrap=hard属性在textarea元素中没有按预期工作?

问题描述 投票:0回答:1

我确实需要换行符,但即使使用wrap =“hard”,定义列,该值仍然是单行。

<!DOCTYPE html>
<html>
<body>

<h1>The textarea wrap attribute</h1>

<textarea id="usrtxt" rows="2" cols="5" name="usrtxt" wrap="hard" style="overflow-wrap: break-word; width: 100px;">
At W3Schools you will find free Web-building tutorials.
</textarea>

<!-- A div to display the textarea content -->
<div id="textareaContent"></div>

<script>
// Function to display textarea content
function showTextareaContent() {
  var textarea = document.getElementById('usrtxt');
  var displayArea = document.getElementById('textareaContent');
  displayArea.innerText = textarea.value;
}

// Event listener for the textarea input
document.getElementById('usrtxt').addEventListener('input', showTextareaContent);

// Initialize the display area with the current content of the textarea
showTextareaContent();
</script>

</body>
</html>

javascript html textarea word-wrap
1个回答
0
投票

wrap属性 - 关键部分是“用于表单提交”。

确实,文本区域的值不包含添加的

\n

通过添加一个包裹textarea的form元素,你可以使用FormData来获取格式化的文本。

<!DOCTYPE html>
<html>
<body>

<h1>The textarea wrap attribute</h1>
<form>
<textarea name="usrtxt" id="usrtxt" rows="2" cols="5" name="usrtxt" wrap="hard" style="overflow-wrap: break-word; width: 100px;">
At W3Schools you will find free Web-building tutorials.
</textarea>
</form>
<!-- A div to display the textarea content -->
<div id="textareaContent"></div>

<script>
// Function to display textarea content
function showTextareaContent() {
  var textarea = document.getElementById('usrtxt');
  let form = textarea.form;
  let fd = new FormData(form);
  let formatted = fd.get("usrtxt"); // this uses the "name" property of the textarea element
  var displayArea = document.getElementById('textareaContent');
  displayArea.innerText = formatted;
}

// Event listener for the textarea input
document.getElementById('usrtxt').addEventListener('input', showTextareaContent);

// Initialize the display area with the current content of the textarea
showTextareaContent();
</script>

</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.