使用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?
使用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")
相关文章:
- 使用Javascript从整个网页中删除具有特定类的所有span标记
- Javascript/jQuery:用HTML span标记替换单引号中的文本
- 用类javascript包装span标记中字符串中的字符索引
- jQuery将文本从span标记复制到另一个span标记
- '对于'循环,替换span标记的问题
- 使用JS将页面中的每个字母设置为随机颜色.为什么在页面的每个打开标记之前总是有一组额外的span标记
- 当我想在span标记中呈现文本时,看到span标记
- 如何选择span标记内的所有内容,包括span标记本身
- 如何将所有文本包装成唯一的span标记
- 使用 中包含的 span 标记的内容对 href 标记的列表进行排序
- 在 jquery 选项卡中查找 span 标记并返回该索引
- 如何将新输入的文本包装到下面已经存在的span标记中
- Jquery:如何在保留文本的同时打开字符串的所有span标记
- 如何在jsp文件的span标记上呈现来自JavaScript的html代码
- 附加的span标记don'我没有指定文本
- 如何在html(span标记)中加载javascript函数
- jquery .bind 或 .change 以填充 Calendar OnClick 中的 span 标记值
- 更改单击的链接 SPAN 标记上的颜色
- 鼠标悬停会影响 span 标记中换行符的取消
- 将表列追加到 td 标记内带有 span 标记的表中