我需要使用javascript将文字添加到网页上,所以我已经按照以下步骤进行了操作
// Create name as h1
var h = document.createElement('h1');
var t = document.createTextNode('Austin Chandler');
h.appendChild(t);
document.body.appendChild(h);
// Formatting h1 tag
document.querySelector('h1').style.color = 'red';
document.querySelector('h1').style.fontFamily = 'Tahoma';
document.querySelector('h1').style.textAlign = 'center';
// Line break
document.write('\n');
// Create course and section number as h2
var h_2 = document.createElement('h2');
var t_2 = document.createTextNode('WEB 115 - Section 0001');
h.appendChild(t_2);
document.body.appendChild(h_2);
// Formatting h2 tag
document.querySelector('h2').style.color = 'red';
document.querySelector('h2').style.fontFamily = 'Garamond';
document.querySelector('h2').style.fontStyle = 'italics';
document.querySelector('h2').style.textAlign = 'center';
[document.write('\n);
仅在我的文本“ Austin Chandler”和“ WEB 115-0001节”之间添加了一个小空格,没有换行。
输出应如下所示:奥斯汀·钱德勒WEB 115-0001节
当前输出看起来像这样:奥斯汀·钱德勒(Austin Chandler)WEB 115-第0001节
如何添加换行符?
在HTML中,换行符为<br>
,由于您的Javascript正在编写HTML,因此您需要使用<br>
。
// Create name as h1
var h = document.createElement('h1');
var t = document.createTextNode('Austin Chandler');
h.appendChild(t);
document.body.appendChild(h);
// Formatting h1 tag
document.querySelector('h1').style.color = 'red';
document.querySelector('h1').style.fontFamily = 'Tahoma';
document.querySelector('h1').style.textAlign = 'center';
// Line break
document.write('<br>');
// Create course and section number as h2
var h_2 = document.createElement('h2');
var t_2 = document.createTextNode('WEB 115 - Section 0001');
h.appendChild(t_2);
document.body.appendChild(h_2);
// Formatting h2 tag
document.querySelector('h2').style.color = 'red';
document.querySelector('h2').style.fontFamily = 'Garamond';
document.querySelector('h2').style.fontStyle = 'italics';
document.querySelector('h2').style.textAlign = 'center';
尝试添加<br>
。会加个休息时间