以可变颜色和可变文本输出文本到页面

Output text to page with a variable color and variable text

本文关键字:文本 输出 变颜色      更新时间:2023-09-26

我试图创建有两个参数的javascript函数:文本和颜色。在代码中,我想传递一个颜色和一些文本。然后代码将以正确的颜色和文本将其写入网页。这是可能的只有javascript还是我必须使用css?

如果您要做的只是为某些给定文本设置颜色,这很容易。我不确定我是否完全理解你想做什么,但从我的理解,这里是一个代码片段,将给你你想要的:

function printIt(text, color) {
    var theEl = document.createElement("p");
    theEl.id = "el";
    var theText = document.createTextNode(text);
    theEl.style.color = color;
    document.body.appendChild(theEl);
    theEl.appendChild(theText);
}
printIt ("hello", "red");

调用printIt()函数时,可以传递参数:textcolor。如果你愿意,你也可以传递一个十六进制的颜色,但这是我能给出的最直接的答案。