[英]How to add variable color to span text
I have a span with some text that changes every time the user clics a button. 我有一个跨度,其中一些文本每次用户单击按钮时都会更改。 I need the color of it to change with every clic (I have the colors in an array like this: var colorArray = ["red","blue","red","red","green","blue","green","red"])
我需要它的颜色随每个clic改变(我在数组中有这样的颜色:var colorArray = [“ red”,“ blue”,“ red”,“ red”,“ green”,“ blue”, “绿色”,“红色”])
The array is not fixed as I read it from DB. 当我从数据库读取数组时,数组未固定。
Any idea on how to do this via javascript (it's for a phonegap project) 关于如何通过javascript执行此操作的任何想法(适用于phonegap项目)
Every time you click on the button you can take the first element of your array and put it at the end of it, so it's a loop. 每次单击按钮时,您都可以获取数组的第一个元素并将其放在数组的末尾,因此这是一个循环。
After with jQuery .css() function you can put the first color of the array to your span
. 使用jQuery .css()函数之后,可以将数组的第一种颜色放入
span
。
Code should look like this : 代码应如下所示:
var colorArray = ["red","blue","green"];
$('button').click(function(){
$('span').css({"color":colorArray[0]});
colorArray.push(colorArray.shift());
});
You can use jQuery and the css() function. 您可以使用jQuery和css()函数。 Please have a look at the documentation for this function at http://api.jquery.com/css/#css2 (there are also some examples in the end of the site).
请在http://api.jquery.com/css/#css2上查看有关此功能的文档(网站末尾还有一些示例)。 In the end you will have something like this:
最后,您将获得以下内容:
$("span#id").css("color", target_color);
Instead of span#id
you have to use the CSS selector for the target <span>
element and target_color
has to be the color of your array, you want to use. 您必须使用CSS选择器代替目标
<span>
元素,而target_color
必须是数组的颜色,而不是span#id
。
If you want pure js Here is the js code: 如果您想要纯js,这是js代码:
<script>
var color = {
currentColor: 0,
colorArray: ["red","blue","red","red","green","blue","green","red","orange"],
changeColor: function(){
document.getElementById('span1').style.color = color.colorArray[color.currentColor];
if (color.currentColor < color.colorArray.length-1){
color.currentColor++;
}else{
color.currentColor = 0;
}
}
};
</script>
Here ir your html: 这是您的html:
<input type="button" value="change color" onclick="color.changeColor()">
<span id="span1"></span>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.