如何在插入的文本中包含换行符

How to include linebreak in inserted text

本文关键字:包含 换行符 文本 插入      更新时间:2023-09-26

我只是想知道在这种特殊的代码情况下如何插入换行符。我通过jQuery的.text()方法显示它。我希望信息和姓名之间有一个换行符。

var textarray = [
    "'"Message'" Name",
];

我试过"'"Message'" 'n Name",但没有成功

这是小提琴http://jsfiddle.net/wa4mej2m/1/

您将通过jQuery的.text()显示文本。字符串中的任何内容都不会导致输出中的换行,因为换行只是HTML元素中的空白——它们不会被特殊解释。

如果您使用.html(),并在字符串中间包含一个<br />标记,情况会更好:

var textarray = [
  "'"Message'"<br /> Name",
];
// later ...
$(this).html(textarray[rannum]).fadeIn('fast');

固定示例:

$(window).load(function() {
  $(window).resize(function() {
    var windowHeight = $(window).height();
    var containerHeight = $(".container").height();
    $(".container").css("top", (windowHeight / 2 - containerHeight * 0.7) + "px");
  });
  var textarray = [
    "'"Example'" <br> Name"
  ];
  var firstTime = true;
  function RndText() {
    var rannum = Math.floor(Math.random() * textarray.length);
    if (firstTime) {
      $('#random_text').fadeIn('fast', function() {
        $(this).html(textarray[rannum]).fadeOut('fast');
      });
      firstTime = false;
    }
    $('#random_text').fadeOut('fast', function() {
      $(this).html(textarray[rannum]).fadeIn('fast');
    });
    var windowHeight = $(window).height();
    var containerHeight = $(".container").height();
    $(".container").css("top", (windowHeight / 2 - containerHeight * 0.7) + "px");
  }
  $(function() {
    // Call the random function when the DOM is ready:
    RndText();
  });
  var inter = setInterval(function() {
    RndText();
  }, 3000);
});
body {
  -webkit-animation: pulse 200s infinite;
  animation: pulse 15s infinite;
}
@-webkit-keyframes pulse {
  0% {
    background: #FBFFF7
  }
  3% {
    background: #FBFFF7
  }
  30% {
    background: #FBFFF7
  }
  60% {
    background: #FBFFF7
  }
  90% {
    background: #FBFFF7
  }
  100% {
    background: #FBFFF7
  }
}
@keyframes pulse {
  0% {
    background: #FBFFF7
  }
  3% {
    background: #FBFFF7
  }
  30% {
    background: #FBFFF7
  }
  60% {
    background: #FBFFF7
  }
  90% {
    background: #FBFFF7
  }
  100% {
    background: #FBFFF7
  }
}
.container {
  position: relative;
  vertical-align: middle;
  margin: auto;
}
#random_text {
  font-size: 3vw;
  text-align: center;
  vertical-align: middle;
  text-align: -moz-center;
  text-align: -webkit-center;
  font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div id="random_text"></div>
</div>

若要换行,如果要在HTML中呈现字符串,则需要添加<br>:

"'"Message'"<br>Name"

如果你不呈现HTML,那就是'n:

"'"Message'"'nName"

在PHP中,您可以使用<br> 完成换行

var textarray = [
    "Message <br> Name"
];
相关文章: