Jquery-在字符串中强制换行时遇到问题

Jquery - Having trouble forcing line breaks in string

本文关键字:换行 遇到 问题 字符串 Jquery-      更新时间:2023-09-26

我有一个字符串,每次一个字符写入屏幕。字符串应该打印在三行上,我试图使用换行符来完成此操作,但整个字符串仍然显示在一行上。我做错了什么?

<?php
include("header.php");
?>
<body>
<div id="content" class="termFont" align="left">
<p>
<p class="caption"></p><p class="cursor">|</p>
</p>
</div>
<script type="text/javascript">
var captionLength = 0;
var caption = "Greetings Professor Falken'n'nA strange game. The only winning move is not to play.'n'nHow about a nice game of chess?";

function cursorAnimation()
{
  $("p.cursor").animate(
  {
    opacity: 0
  }, "fast", "swing").animate(
  {
    opacity: 1
  }, "fast", "swing");
}
$(document).ready(function()
{
    blinkingCursor();
 setInterval ( "cursorAnimation()", 600 );
});
function blinkingCursor()
{
  type();
}
function type()
{
  $('p.caption').html(caption.substr(0, captionLength++));
  if(captionLength < caption.length+1)
  {
    setTimeout("type()", 50);
  }
  else
  {
    captionLength = 0;
    caption = "";
  }
}
</script>
</body>
</html>

<br>而不是"''n"添加到字符串中。HTML通常不关心空白(除非设置了这样的样式)。

同样,当你调用setTimeout()时,这样做:

setTimeout(type, 50);

使用字符串可能会导致各种奇怪的问题,而且很少有必要这样做。

编辑—至于我对HTML样式的评论,您可能会为"caption"元素在CSS中添加"white-space:pre"。然后你的换行符就会被遵守。