如何在插入的文本中包含换行符
如何在插入的文本中包含换行符
我只是想知道在这种特定的代码情况下如何插入一个换行符。我是通过jQuery的.text()
方法来显示它的。我希望在消息和名称之间有一个换行符。
var textarray = [ "\"消息\" 名称", ];
我尝试过"\"消息\" \n 名称"
,但没有成功。
这是jsfiddle的链接:http://jsfiddle.net/wa4mej2m/1/
在PHP中,可以使用<br>标签来实现换行。
在JavaScript中,可以使用数组来存储多行文本,如下所示:
var textarray = [ "Message <br> Name" ];
然而,如果我们想要在插入的文本中包含换行符,可能会遇到问题。具体问题如下:
- 在PHP中,如果我们直接在双引号中插入换行符,它们将被解析为普通的文本,而不是换行符。
- 在JavaScript中,如果我们直接在数组中的字符串中插入换行符,它们也会被解析为普通的文本,而不是换行符。
为了解决这个问题,我们可以采用以下方法:
- 在PHP中,我们可以使用双引号字符串中的转义字符\n
来表示换行符。例如:"Message\nName"
。
- 在JavaScript中,我们可以使用反斜杠加n
的方式来表示换行符。例如:"Message\nName"
。
这样,我们就可以在插入的文本中包含换行符了。
问题的原因是使用jQuery的.text()方法显示文本时,无论在字符串中放入什么内容都不会在输出中引起换行,因为换行只是HTML元素中的空格,不会被特殊解释。
解决方法是使用.html()方法替代.text()方法,并在字符串中插入
标签,如下所示:
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; }
Okay so if I understand correctly, I just have to add $(this).html(textarray[rannum]).fadeIn('fast'); underneath var textarray = [ "\"Message\"<br /> Name", ]; ? No. You replace the $(this).text(...) stuff in your example with $(this).html(...). See the code snippet included here, which is just your jsFiddle with that change already made.
文章结束。