如何在此分隔符中按行分隔文本

How do I seperate text by lines in this divider?

本文关键字:分隔 文本 分隔符      更新时间:2023-09-26
<html>
<head></head>
<body>
<center>
    <div id="output" style="width:1000px; height:800px; background-color:grey; word-wrap: break-word;"></div> //divider is here
</center>
</body>
<script>
var printOut = function(text) {
  var output = document.getElementById("output");
  output.innerHTML += text;
};
var userChoice = prompt("Do you choose Rock, Paper, or Scissors?") 
    console.log(printOut("You chose " + userChoice + ".")); //Used here..
var computerChoice = Math.random();
  if (computerChoice < 0.34) {
    computerChoice = "Rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "Paper";
} else {
    computerChoice = "Scissors";
} console.log(printOut("The computer chooses " + computerChoice + ".")); //Here too..
var compareChoice = function(userChoice, computerChoice) {
    if(userChoice === computerChoice) {
        return "The result is a tie!";
    }    
    if (userChoice === "Rock") {
       if(computerChoice === "Scissors") {
            return "You win! Rock smashes Scissors!";
        } else {
            return "You lose! Paper covers Rock!";
        }
    }    
    if (userChoice === "Paper") {
        if(computerChoice === "Rock") {
            return "You win! Paper covers Rock!";
        } else {
            return "You lose! Scissors cut Paper!!"
        }
    }    
    if (userChoice === "Scissors") {
        if (computerChoice === "Paper") {
            return "You win! Scissors cut Paper!";
        } else {
            return "You lose! Rock smashes Scissors!";
        }
    }
};
console.log(printOut(compareChoice(userChoice, computerChoice))); //Lastly, here.

</script>
</html>

如何将结果放在单独的行上,如:

"你选择了Rock.

计算机选择了剪刀。

石头砸剪刀。你赢了!"

相对

"你选择了Rock。电脑选择了剪刀。石头砸剪刀。你赢了!"

在HTML中,<br />标记用于分隔行。但是,您也可以使用<pre></pre>将文本呈现为代码。然后,您可以使用魔术结尾字符:' 'n'来分隔。

如果你想使用'n,你的HTML必须像这样:

<center>
    <pre id="output" style="width:1000px; height:800px; background-color:grey; word-wrap: break-word;"></pre> //divider is here
</center>

在这种情况下,将'n放在需要新建行的地方。此外,每个空格( )将被渲染-就像在StackOverflow上的灰色代码块一样。

或者,你也可以在任何元素上使用whitespace:pre样式。

JSFiddle示例如何正确添加和创建日志

注意:我要警告您,将文本附加到HTML中作为string将导致浏览器重新解析该节点中的HTML。当日志较长时,这可能会导致延迟。

这是添加纯文本的正确方法:

function addText(text, idOrNode) {
    if(idOrNode.tagName==null)
      idOrNode = document.getElementById(idOrNode);
    if(idOrNode==null)
      throw new Error("Can't append text - the element is invalid.");
    var text_element = document.createTextNode(text);
    idOrNode.appendChild(text_element);
}

强制它们出现在新行上的方法不止一种,但最简单的方法是在要开始新行的字符串中添加换行标记<br>。例如:

console.log(printOut("You chose " + userChoice + ".<br>"));

或者,您可以像<div><p>那样将每一行文本换行到块html元素中,如下所示:

console.log(printOut("<p>You chose " + userChoice + ".</p>"));