使用JS将页面中的每个字母设置为随机颜色.为什么在页面的每个打开标记之前总是有一组额外的span标记

Setting each letter in page to a random color with JS. Why are there always an extra set of span tags before each opening tags of the page?

本文关键字:span 标记 一组 设置 JS 随机 使用 为什么 颜色      更新时间:2023-09-26

使用Google Drive 托管的页面

JS

var part_of_doc = false;  //a character has been found that is not part of the visible document
var body;
//will be used to generate random rgb
function randint(max, min) {
    return Math.floor((Math.random() * (max - min)) + min);
}
//generate a random rgb(x,y,z) string
function randRGB(){
    var color = "rgb(";
    for (var i = 0; i < 3; i++) {
        color += randint(0, 255).toString() + ",";
    }
    color = color.substring(0, color.length - 1);  //formatting the rgb to
    color += ')';  //be a proper rgb value
    return color;
}
//returns a character surrounded by a set of spans with a random background-color rgb value 
function spanify(char){
    var open_span = '<span style="color:' + randRGB() + '">';
    return open_span + char + '</span>';  //return the opening tag of a random color rgb tag, character, and a closing span
}
body = document.body.innerHTML;
for (var i=body.length - 1; i>=0; i--){
    body = document.body.innerHTML;  //update body
    console.log(body[i], i);
    if (body[i] == ">") {  //the upcoming characters are part of an html tag and should be ignored
        part_of_doc = false;
        console.log(false);
    } else if (body[i] == "<") {  //the following characters may be part of the visible page and should not be ignored
        part_of_doc = true;
        console.log(true);
    } else if (part_of_doc == true && body[i] != " ") {  //found a character that is part of the visible page
        console.log("changing?");
        document.body.innerHTML = body.substring(0, i) + spanify(body[i]) + body.substring(i + 1, body.length);  //insert a span with a random color to the page surrounding a letter of the page
        console.log(document.body.innerHTML);
    }
}

如果你检查页面中的元素,你会发现在每个不是直接子标签的打开标签之前都有一组span。JS的目标是随机给页面上的每个字母上色,所以我想消除这个小故障,尽管这并不重要,因为目标仍然完成。有人能说出为什么会发生这种事吗?我不知道为什么算法会区分开放标签和封闭标签,它应该看到它们完全相同。

您正在为换行符-"'n"和可能的"'r"字符着色。检查body[i]是否不是其中之一,然后再对其进行spany:

else if (part_of_doc == true && body[i] != " " && body[i] != "'r" && body[i] != "'n")