Javascript 更改每一个新的“字体颜色”;附加“;功能
我有一个页面,我正在使用append函数每5秒添加一行新的文本(“.newText”) 这就是我目前拥有的:Javascript 更改每一个新的“字体颜色”;附加“;功能,javascript,jquery,colors,append,Javascript,Jquery,Colors,Append,我有一个页面,我正在使用append函数每5秒添加一行新的文本(“.newText”) 这就是我目前拥有的: var fontColors var randomColor $(function(){ fontColors = ['red','orange','yellow','green','blue','indigo','violet','pink'] randomColor = fontColors[Math.floor(Math.random
var fontColors
var randomColor
$(function(){
fontColors = ['red','orange','yellow','green','blue','indigo','violet','pink']
randomColor = fontColors[Math.floor(Math.random() * fontColors.length)]
$('.newText').css({
'color':randomColor
})
$('.newText').append('<p>original line of text</p>')
setInterval(function(){
$('.newText').append('<p>this text is added every 5 seconds</p>')
randomColor = fontColors[Math.floor(Math.random() * fontColors.length)]
$('.newText').css({
'color':randomColor
})
}, 5000)
})
})
var-fontColors
随机颜色
$(函数(){
FontColor=[“红色”、“橙色”、“黄色”、“绿色”、“蓝色”、“靛蓝”、“紫色”、“粉色”]
randomColor=fontColors[Math.floor(Math.random()*fontColors.length)]
$('.newText').css({
“颜色”:随机颜色
})
$('.newText').append('文本的原始行'))
setInterval(函数(){
$(“.newText”).append(“此文本每5秒添加一次”
randomColor=fontColors[Math.floor(Math.random()*fontColors.length)]
$('.newText').css({
“颜色”:随机颜色
})
}, 5000)
})
})
所以现在它每5秒改变一次屏幕上所有文本的颜色(很明显)。我希望每一行都有不同的颜色,但我不希望更改先前附加的文本行的颜色。这应该可以做到。不是将颜色添加到
.newText
,而是添加到新添加的行
var;
颜色;
$(函数(){
FontColor=[“红色”、“橙色”、“黄色”、“绿色”、“蓝色”、“靛蓝”、“紫色”、“粉色”]
randomColor=fontColors[Math.floor(Math.random()*fontColors.length)]
$('.newText').css({'color':randomColor});
$('.newText').append('文本的原始行');
setInterval(函数(){
var newLine=$(“此文本每5秒添加一次”);
$('.newText').append(换行符)
randomColor=fontColors[Math.floor(Math.random()*fontColors.length)]
$(换行符).css({
“颜色”:随机颜色
})
}, 5000)
})
您可以将内联css添加到您的
p
标记中,如下所示:
$('.newText').append('<p style="color: ' + randomColor + '">this text is added every 5 seconds</p>')
$('.newText').append('此文本每5秒添加一次)
请参见下面的工作示例:
var-fontColors
随机颜色
$(函数(){
FontColor=[“红色”、“橙色”、“黄色”、“绿色”、“蓝色”、“靛蓝”、“紫色”、“粉色”]
randomColor=fontColors[Math.floor(Math.random()*fontColors.length)]
$('.newText').append('文本的原始行
'))
setInterval(函数(){
randomColor=fontColors[Math.floor(Math.random()*fontColors.length)]
$('.newText').append('此文本每5秒添加一次)
}, 5000)
})
创建一个
元素,将CSS添加到该元素中,然后将其添加到newText
元素中,而不是更改newText
元素本身的CSS。因此,将其添加到p元素中……非常完美。非常感谢@埃维罗:不用担心,很乐意帮忙