完全尊重空白和换行符的资源字符串

Respect exactly the resource string for white-spacing and newlines

(我只是简单地回答了我之前在此线程中提出的问题)。

我正在尝试在 HTML 中配置文本区域。我希望它完全按照资源字符串中有关空白和换行符的说明进行操作(换行除外)。

例如,给定一个字符串1234,\n 5678, 1234567890123456789\n 123\n表示换行,space表示空格。因此,我希望它按如下方式打印在文本区域中:

1234,
  5678, 12345678901234
56789
  123

注意 1234567890123456789 被换行了,因为它达到了文本区域的最大宽度。这是完全正常的,也是我所期望的。

但是,我当前的代码没有给出正确的输出,这里是代码:

<!DOCTYPE html>
<html>
<body class="ms-font-m">
    <textarea id="myTextarea" style="font-size: 16px; font-family: monospace; height: 15em; resize: none; white-space: pre-line;"></textarea>
    <script>
        document.getElementById("myTextarea").value = "1234,\n  5678, 1234567890123456789\n  123"
    </script>
</body>
</html>

结果如下:

有谁知道如何修改代码以使其打印出我期望的内容?

PS:整个JSBin

PS: white-space的关键词我都试过了page,没有一个给我满意的结果...

由于字体、字母大小或宽度大小,它似乎会进入下一行,但我没有得到你得到的输出,它不会进入下一行。宽度为 20em 时它不起作用,但宽度为 18em 时它起作用。您想让 DDDDDD.... 的大文本滚动还是不换行?使用 white-space:nowrap;而不是预线。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <title>Title</title>  
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.min.js"></script>
    <link href="Office.css" rel="stylesheet" type="text/css" />
    <script src="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js" type="text/javascript"></script>
    <link href="Common.css" rel="stylesheet" type="text/css" />
    <script src="Notification.js" type="text/javascript"></script>
    <script src="Home.js" type="text/javascript"></script>
    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.min.css">
    <link rel="stylesheet" href="https://appsforoffice.microsoft.com/fabric/1.0/fabric.components.min.css">
    <style>
    .ms-TextField.ms-TextField--multiline .ms-TextField-field {
    font-family: monospace;
    height: 15em; 
    resize: none;
    white-space: nowrap;
    width: 10em;
    overflow: hidden;
    }
    </style>
</head>
<body class="ms-font-m">
    <div id="content-main">
    <div class="padding">
    <div class="ms-TextField ms-TextField--multiline">
        <textarea class="ms-TextField-field" id="myTextarea" spellcheck=false style="font-size: 16px;"></textarea>
    </div>
    <script>
        document.getElementById("myTextarea").value = "=AAAA,\n  BBBB, DDDDDDDDDDDDDDDDDDDDDDDDD\n  CCCC"
    </script>
    </div>
</body>
</html>

Original answer: 如何调整 textarea width 的大小以便内容包含在他们的行分别没有溢出但尊重断点 \n.


在我原来的回答中,我误解了你的意思。在收到反馈后,我发现我的做法是错误的,所以这里是您问题的解决方案。

如果您希望单词在溢出时进入下一行并同时尊重空格,您只需删除 white-space: pre-line; 并添加 word-break: break-all; 属性。

document.getElementById("myTextarea").value = "1234,\n  5678, 1234567890123456789\n  123"
#myTextarea{
  font-size: 16px; 
  font-family: monospace; 
  height: 15em; 
  resize: none;
  word-break: break-all;
}
<textarea id="myTextarea" style=""></textarea>