You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让JavaScript数组随机取出的长文本在输入框自动换行?

解决长文本自动换行问题

你的问题核心是**input[type="text"]是单行输入控件**,它天生不支持多行文本自动换行——哪怕你设置了height属性,只是拉长了控件的高度,文本依然会横向溢出被截断,这就是你之前加换行符、设置CSS都没用的原因。下面给你两种可行的解决方案:

方案一:替换为<textarea>(推荐)

<textarea>是原生支持多行文本的控件,能自动处理换行,还可以设置只读防止用户编辑。

修改后的完整代码:

<style>
.button {
  background-color: #094997;
  border-radius: 12px;
  border: none;
  color: white;
  padding: 12px 20px;
  text-align: center;
  text-decoration: none;
  font-size: 24px;
  width: 200px;
}
/* 调整textarea样式 */
textarea {
  font-size: 22px;
  padding: 50px 50px;
  text-align: center;
  width: 200px;
  height: 250px;
  /* 关键:自动换行 */
  white-space: pre-wrap;
  /* 可选:禁止用户调整文本框大小 */
  resize: none;
  /* 可选:去掉默认的边框样式,和原input一致 */
  border: 1px solid #ccc;
  border-radius: 4px;
}
.questionsdiv {
  text-align: center; 
}
</style>

<div class="questionsdiv">
<!-- 把input换成textarea,添加readonly属性(可选) -->
<textarea id="randomquestion" readonly></textarea>
<br><br>
<button class="button" onclick="findquestion();">Random Question</button>
</div>

<script>
const question = ["How old are you?","Where do you go on Saturdays?","Do you have any brothers or sisters?","How many books do you own?","Who is your favorite music artist lately?","Do you like Jazz music?","Have you ever traveled outside of Japan?","Do you want to live in the countryside or in the city when you are older and have a family?",];

function findquestion() {
  let randomIndex = Math.floor(Math.random() * question.length);
  // textarea用value属性设置内容,不用setAttribute
  document.getElementById("randomquestion").value = question[randomIndex];
}
</script>

关键改动点:

  1. 替换<input>为<textarea>,并添加readonly属性(如果不需要用户编辑问题)
  2. 给textarea添加white-space: pre-wrap;CSS属性,确保文本能自动换行
  3. JS中改用element.value设置内容,而非setAttribute("value")

方案二:用<div>纯展示(如果不需要输入功能)

如果只是展示问题,不需要用户输入,用div更合适,样式也更容易控制:

修改后的核心代码片段:

<!-- 替换input为div -->
<div id="randomquestion" class="question-display"></div>
.question-display {
  font-size: 22px;
  padding: 50px 50px;
  text-align: center;
  width: 200px;
  height: 250px;
  border: 1px solid #ccc;
  border-radius: 4px;
  /* 自动换行 */
  word-wrap: break-word;
  /* 确保容器高度足够时能换行 */
  overflow-wrap: break-word;
}
function findquestion() {
  let randomIndex = Math.floor(Math.random() * question.length);
  document.getElementById("randomquestion").textContent = question[randomIndex];
}

说明:

  • word-wrap: break-word;和overflow-wrap: break-word;能让长单词或文本自动换行到下一行
  • 用textContent设置内容比innerHTML更安全,避免XSS风险

内容的提问来源于stack exchange,提问作者Schoonmaker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:10:21