我正在尝试创建一个脚本,在我的网站上的“p”标签内的每个字母都是随机颜色。着色部分工作正常,问题是我的脚本覆盖了“br”和“a”标签。有没有解决方法呢?
到目前为止,这是我的代码:
function changeColor() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
var innerText = paragraphs[i].innerText;
var innerTextSplit = innerText.split("");
paragraphs[i].innerText = ""
for(var j = 0; j < innerTextSplit.length; j++) {
var randomColor = "rgb(" + Math.floor((Math.random() * 255) + 1) + ", " + Math.floor((Math.random() * 255) + 1) + ", " + Math.floor((Math.random() * 255) + 1) + ");"
innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
paragraphs[i].innerHTML += innerTextSplit[j];
}
}
}
非常感谢任何帮助,在此先感谢:)
-jAndersen
答案 0 :(得分:0)
请在下面的代码段中找到一个用于生成随机颜色hexa代码的函数getRandomColor()
$(function(){
changeColor();
});
function changeColor() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
var innerText = paragraphs[i].innerText;
var innerTextSplit = innerText.split("");
paragraphs[i].innerText = ""
for(var j = 0; j < innerTextSplit.length; j++) {
var randomColor =getRandomColor();
innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
paragraphs[i].innerHTML += innerTextSplit[j];
}
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>geloosmsd</p>
<p>geloosmsd</p>
<p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p><p>geloosmsd</p>
&#13;
答案 1 :(得分:0)
不优雅,但请尝试:
function changeColor() {
var paragraphs = document.getElementsByTagName("p");
for(var i = 0; i < paragraphs.length; i++)
{
var innerText = paragraphs[i].innerHTML;
var innerTextSplit = innerText.split("");
paragraphs[i].innerText = "";
var isHTMLElement = false;
for(var j = 0; j < innerTextSplit.length; j++) {
if(innerTextSplit[j] == "<")
isHTMLElement = true;
if(!isHTMLElement){
var randomColor = "rgb(" + Math.floor((Math.random() * 255) + 1) + ", " + Math.floor((Math.random() * 255) + 1) + ", " + Math.floor((Math.random() * 255) + 1) + ");"
innerTextSplit[j] = '<span style="color: ' + randomColor + '">' + innerTextSplit[j] + '</span>';
}
if(innerTextSplit[j] == ">")
isHTMLElement = false;
}
innerTextSplit = innerTextSplit.join('');
paragraphs[i].innerHTML += innerTextSplit;
}
}