【问题标题】:How to make numbers entered with JS not overlow the container but just go to the next line? [duplicate]如何使用 JS 输入的数字不会超过容器而只是转到下一行? [复制]
【发布时间】:2021-12-09 22:48:29
【问题描述】:

我想做一个简单的类似计算器的应用程序。我创建了一个 div,其 ID 为 display 和三个输入数字 1、2、3 的按钮。这些数字彼此相邻显示。然而,当它们撞到容器的边缘时,它们就不会包裹起来。如何使输入的数字换行到下一行?我试过:显示:弹性;弹性包装:换行;但它没有用。我猜溢出:隐藏;也不起作用,因为它只隐藏了内容。

  <div id="display"></div>
    <div class="keypad">
      <button id="btn1" onclick="press1()">1</button>
      <button id="btn2" onclick="press2()">2</button>
      <button id="btn1" onclick="press3()">3</button>
  </div>
  #display {
    width: 300px;
    height: 100px;
    background-color: gold;
    border: 1px solid black;
  }

  .keypad {
    width: 300px;
    height: 100px;
    margin: 0 auto;
    border: 1px solid orangered;
  }

  button {
    width: 97px;
    height: 97px;
    border: 0;
    outline: 0;
  }

  let numberEntered = "";
  const display = document.querySelector("#display");
  console.log(display);

  function press1() {
    numberEntered = 1;
    display.textContent += `${numberEntered}`;
  }

  function press2() {
    numberEntered = 2;
    display.textContent += `${numberEntered}`;
  }

  function press3() {
    numberEntered = 3;
    display.textContent += `${numberEntered}`;
  }

【问题讨论】:

  • word-break:break-word 在水平方向有效,但在垂直方向仍然溢出。我猜溢出隐藏是解决方案和填充。除非其他人,可以提出任何建议吗?

标签: javascript css


【解决方案1】:

尝试将此行添加到#display (CSS):

word-wrap: break-word;

我希望这就是你的意思。

编辑 - 反应:垂直溢出,因为您将高度定义为 100px,它不能变大。我不知道文本到达末尾后您到底希望文本做什么。您可以将其添加到 CSS min-height: 100px; height: fit-content; 并且您的#display 会随着您添加更多数字而膨胀。您也可以添加overflow-y: scroll;,框不会改变它的大小,它只会添加滚动条。如果您可以指定,当数字到达末尾时框的预期行为,我也许可以改进我的答案。

【讨论】:

  • 它在水平方向工作,但在垂直方向仍然溢出。
猜你喜欢
  • 1970-01-01
  • 2019-07-23
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
  • 2021-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多