[英]How to change the font and colour of individual array elements
用户可以在屏幕上的任意位置单击,然后段落将在用户选择的鼠标位置上一个接一个地打印出来。 但是我想让这些段落在不同的 styles 中,所以我的问题是,数组中的每个段落如何有不同的 css 元素? 任何帮助将非常感激。
const texts = [
"Paragraph: 1",
"Paragraph: 2",
"Paragraph: 3",
"Paragraph: 4",
"Paragraph: 5",
"Paragraph: 6",
"Paragraph: 7",
"Paragraph: 8",
"Paragraph: 9",
"Paragraph: 10"
];
// Keeps Track of Current Text
let currentParaIdx = 0;
document.addEventListener("click", (e) => {
// Stop once All Texts are Displayed
if (currentParaIdx === texts.length) return;
const { clientX, clientY } = e; //get the click position
//create the div
const div = document.createElement("div");
//set its text
div.innerText = texts[currentParaIdx];
currentParaIdx++;
//set its position and position style
div.style.position = "absolute";
div.style.left = clientX + "px";
div.style.top = clientY + "px";
document.body.append(div); //add div to the page
});
到目前为止,这是我的代码,那么如何将 css 合并到这些单独的段落中?
因此,一种方法是为每个元素设置一个 class。 将所有类放在一个数组中,如文本,并将相关类分配给相关元素的类列表。 但是,如果您有未定义数量的元素,并且每个元素都需要不同的 class,您可能希望有一个公共的 class 用于公共功能,并根据每个段落的需要修改 styles。
const texts = [ "Paragraph: 1", "Paragraph: 2", "Paragraph: 3", "Paragraph: 4", "Paragraph: 5", "Paragraph: 6", "Paragraph: 7", "Paragraph: 8", "Paragraph: 9", "Paragraph: 10" ]; const classes = [ "red gray-bg font-1", "blue font-2", "red", "blue", "red", "blue", "red", "blue", "red", "blue", ]; // Keeps Track of Current Text let currentParaIdx = 0; document.addEventListener("click", (e) => { // Stop once All Texts are Displayed if (currentParaIdx === texts.length) return; const { clientX, clientY } = e; //get the click position //create the div const div = document.createElement("div"); //set its text div.innerText = texts[currentParaIdx]; //set its position and position style div.classList=classes[currentParaIdx]; div.style.position = "absolute"; div.style.left = clientX + "px"; div.style.top = clientY + "px"; currentParaIdx++; document.body.append(div); //add div to the page });
.red{color:red}.blue{color:blue}.gray-bg{ background:darkgreen;} /*CHANGE TEXT TO ELEMENT TO THIS CLASS*/.font-1{font-style:italic; font-family:'system-ui'}.font-2{font-style:italic; font-family:'serif'} /*CHANGE TEXT TO ALL ELEMENTS*/ *{ font-family: Arial, Helvetica, sans-serif;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.