如何将 javascript 变量导入 CSS 并设置它们的样式?

How to import javascript variables into CSS and style them?

我对 javascript 很陌生。我正在尝试创建一个网站,您可以在其中输入您的出生时间并以天为单位找出您的年龄。我的输出(变量)也在 JS 中,那么如何导入它并在 CSS 中设置样式?

这是 Javascript 代码:

function ageInDays() {
  // variables
     var birthYear = prompt("What Year Were You Born In?");
     var ageInDayss = (2021 - birthYear) * 365;
     var textAnswerYikes = "Yikes... that's old"

 // variable CSS

 //text
    var h1 = document.createElement('h1');
    var textAnswer = document.createTextNode("You are " + ageInDayss + " days old. " + 
    textAnswerYikes)
    h1.setAttribute('id', 'ageInDays');
    h1.appendChild(textAnswer);
    document.getElementById('flex-box-result').appendChild(h1);
}

我假设你的 'import' 意味着你的 h1 在 HTML 中。如果是这样,您只需将 h1 附加到 HTML 正文或您希望包含在其中的任何其他 HTML 元素(例如 div)。

您的 JavaScript 文件:

//text
   var h1 = document.createElement('h1');
   // add inner text to your h1 using string template literal.
   h1.innerText = `You are ${ageInDayss} days old. ${textAnswerYikes}`;
   h1.setAttribute('id', 'ageInDays');

   document.body.append(h1) // <- append your h1 into HTML body or other HTML element
   document.getElementById('flex-box-result').appendChild(h1);

要设置 h1 的样式,您只需 select 您分配给它的 ID (ageInDays) 并在您的 CSS 文件中设置样式。

您的 CSS 文件:

#ageInDays {
 /* your CSS styling code goes here */
}

希望这能回答您的问题。