是否可以在text ="中创建换行符"?例如,我希望早上好的问候是:早上好! (换行)你今天好吗?。
我已经尝试过\ n,如此:text ="早上好!" +" \ n" +"你今天过得怎么样?"。
有什么建议吗?
这是我的代码:
var myDate = new Date();
var text = "";
/* hour is before noon */
if (myDate.getHours() < 12) {
text = "Good Morning!";
}
/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if (myDate.getHours() >= 12 && myDate.getHours() <= 17) {
text = "Good Afternoon!";
}
/* the hour is after 5pm, so it is between 6pm and midnight */
else if (myDate.getHours() > 17 && myDate.getHours() <= 24) {
text = "Good Evening!";
}
/* the hour is not between 0 and 24, so something is wrong */
else {
text = "Hallo!";
}
$("#rowheader h1").text(text);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rowheader">
This is where the magic happens
<h1></h1>
</div>
&#13;
答案 0 :(得分:1)
你可以在文本变量中插入一个换行符,并使用.html()代替.text(),如下所示:
var myDate = new Date();
var text = "";
/* hour is before noon */
if (myDate.getHours() < 12) {
text = "Good Morning! <br /> How are you today?";
}
/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if (myDate.getHours() >= 12 && myDate.getHours() <= 17) {
text = "Good Afternoon! <br /> How are you today?";
}
/* the hour is after 5pm, so it is between 6pm and midnight */
else if (myDate.getHours() > 17 && myDate.getHours() <= 24) {
text = "Good Evening! <br /> How are you today?";
}
/* the hour is not between 0 and 24, so something is wrong */
else {
text = "Hallo!";
}
$("#rowheader h1").html(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rowheader">
<h1></h1>
</div>
答案 1 :(得分:0)
您可以选择使用更多标签吗?
<div id="rowheader">
<h1 id="headerline1"></h1>
<h1 id="headerline2">How are you today?</h1>
</div>
如果需要,您可以使用CSS调整外观......在您的JS代码中:
$("#headerline1").text(text);
答案 2 :(得分:0)
应用一些CSS技巧。
示例h1标签:
<h1 id="yourheader" class="test">
</h1>
脚本:
var value = "good morning!" + "\n" + "How are you today?";
$('#yourheader').html(value);
CSS:
.test{
white-space:pre-wrap;
}
答案 3 :(得分:0)
我认为你可以使用jquery html方法,而不是这样:
text += "<br/>";
text += "How are you today?";
$("#rowheader h1").html(text);
答案 4 :(得分:0)
为了在html文档中直观地显示换行符,您需要部署元素<br>
。
因此,虽然您的原始脚本为textContent
创建h1
,但为innerHTML
创建h1
可能是更好的方法,而不是:
var heading = document.getElementById('rowheader').getElementsByTagName('h1')[0];
var myDate = new Date();
var html = '';
/* hour is before noon */
if (myDate.getHours() < 12) {
html = 'Good Morning!';
}
/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if (myDate.getHours() >= 12 && myDate.getHours() <= 17) {
html = 'Good Afternoon!';
}
/* the hour is after 5pm, so it is between 6pm and midnight */
else if (myDate.getHours() > 17 && myDate.getHours() <= 24) {
html = 'Good Evening!';
}
/* the hour is not between 0 and 24, so something is wrong */
else {
html = 'Hallo!';
}
html += '<br />How are you today?';
heading.innerHTML = html;
&#13;
<div id="rowheader">
This is where the magic happens
<h1></h1>
</div>
&#13;