gpt4 book ai didi

javascript - 如何使用通过 JavaScript 函数创建的 CSS 来设置 DOM 元素的样式

转载 作者:行者123 更新时间:2023-11-28 13:00:24 25 4
gpt4 key购买 nike

我有一个创建一些 DOM 节点的 JavaScript 函数:

function setHeader(){
var questionBox = document.createElement("div");
questionBox.setAttribute("id","question" + (questionNumber + 1));
document.body.insertBefore(questionBox,scriptBox);
var questionElement = document.createElement("h3");
// questionElement.setAttribute("id","question" + (questionNumber + 1));
var questionText = document.createTextNode(questions[questionNumber].question);
questionElement.appendChild(questionText);
questionBox.appendChild(questionElement);
$(questionBox).hide().fadeIn(1000);
}

此函数创建以下 HTML:

<div id="questionHolder">
<h3 id="question">Is the sky blue?</h3>
</div>

我想知道如何使用 CSS 设置 divh3 元素的样式?

我假设 CSS 文件在创建 DOM 节点之前被读取,因为 CSS 链接在 header 中,而我的 JavaScript 文件链接在我的 body 标签的末尾页面。

我认为这意味着 CSS 样式不会应用于创建的元素,我的测试也同意这一点。

谢谢,感谢任何帮助。

编辑:

我更改了问题中的函数以使其更易于阅读。 actually 函数从数组中提取问题:

function setHeader(){
var questionBox = document.createElement("div");
questionBox.setAttribute("id","question" + (questionNumber + 1));
document.body.appendChild(questionBox);
var questionElement = document.createElement("h3");
questionElement.setAttribute(questions[questionNumber].question));
var questionText = document.createTextNode("Is the sky blue?");
questionElement.appendChild(questionText);
questionBox.appendChild(questionElement);
}

这似乎对我不起作用。这会改变什么吗?

最佳答案

只需在你的脚本中添加样式属性,它就会为你工作,

questionBox.setAttribute("style",""background-color":"yellow"");

您的代码将如下所示,

function setHeader(){
var questionBox = document.createElement("div");
questionBox.setAttribute("id","questionHolder");
questionBox.setAttribute("style",""background-color":"yellow"");
document.body.appendChild(questionBox);
var questionElement = document.createElement("h3");
questionElement.setAttribute("id","question");
var questionText = document.createTextNode("Is the sky blue?");
questionElement.appendChild(questionText);
questionBox.appendChild(questionElement);
}

关于javascript - 如何使用通过 JavaScript 函数创建的 CSS 来设置 DOM 元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21450854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com