使用 document.getElementById("").innerHTML 时如何更改段落文本的字体?

How to change the font of paragraph text when using document.getElementById("").innerHTML?

我正在根据用户输入构建一个抄本,我想知道是否有人可以指出我如何能够更改存储在 text_to_add_one 和中的字符串的字体样式的正确方向text_to_add_two.

if (build_transcript) {
    var text_to_add_one = "<b>" + "YOU: " + "</b>" + `${transcript_you}`;
    var text_to_add_two = "<b>" + "COMPUTER: " + "</b>" + `${transcript_computer}`; 
    document.getElementById("wordsIncluded").innerHTML += "<p>" + text_to_add_one + "</p>" + "<p>"+ text_to_add_two + "</p>" + "</br>";
   build_transcript = false;
}

//wordsIncluded is a div

我已经尝试了下面的方法,但它似乎不起作用!

 document.getElementById("wordsIncluded").innerHTML += "<p id="changeFont">" + text_to_add_one + "</p>" + "<p id="changeFont">" + text_to_add_two + "</p>" + "</br>";

CSS 文件

#changeFont {
      font-style: 'Quicksand';
}

你不应该使用 "<p id="changecolor">"。正如代码着色所示,字符串的一部分无关紧要。您应该使用 "<p id=\"changecolor\">"'<p id="changecolor">'

您需要使用单引号。

document.getElementById("wordsIncluded").innerHTML += '<p id="changeFont">' + text_to_add_one + '</p>' + '<p id="changeFont">' + text_to_add_two + '</p>' + '</br>';

尝试下面的操作。

const transcript_you = "me";
const transcript_computer = "mac";

var text_to_add_one = `<b>YOU: </b>${transcript_you}`;
var text_to_add_two = `<b>COMPUTER: </b>${transcript_computer}`;

document.getElementById(
  "wordsIncluded"
).innerHTML += `<p class="changeFont">${text_to_add_one}</p><p class="changeFont">${text_to_add_two}</p></br>`;
p.changeFont {
  color: red;
}
<div id="wordsIncluded"></div>

顺便说一句,这也有效,我可能会使用它,因为我可以看到 font-family 我将使用什么:

document.getElementById("wordsIncluded").innerHTML += `<p style="font-family: 'Quicksand'; class="changeFont">${text_to_add_one}</p><p style="font-family: 'Quicksand'; class="changeFont">${text_to_add_two}</p></br>`;