javascript two color repeating effect
Is there a way to repeat two colors one ofther another with javascript.. For example I have some text in 3 different boxes.
- Text 1
- Text 2
- Text 3
Now I want the 1 and 3 to be with red and the second to be开发者_开发知识库 black.. now every time I add some new line, the colors to change, if I add Text 4 - to be - black, then Text 5 - red.
Is there a way to do this only with js ?
You can do it with jQuery's odd selector or even selector its 0-based so:
In particular, note that the 0-based indexing means that, counter-intuitively, :odd selects the second element, fourth element, and so on within the matched set.
let's say you have these li elements:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
and the following css:
.red{
color: red;
}
.green{
color: green;
}
and if you use jQuery and do this get the element and attach class name for the appropriate color scheme for odd or even:
console.log($('li:odd')); //[<li>2</li>, <li>4</li>] you'll get these elements
console.log($('li:even')); //[<li>1</li>,<li>3</li>,<li>5</li>] you'll get these
$('li:odd').addClass(' red'); // turn color to red
$('li:even').addClass(' green'); //turn color to green
or in regular JavaScript:
var myLi = document.getElementsByTagName('li');
for(var i=0; i<myLi.length; i++){
if(i%2 == 0)
myLi[i].className += ' red';
else
myLi[i].className += ' green';
}
You can use jQuery to do that, but if you're a beginner, it's better to learn some vanilla JS first.
function isOdd(num) {
return num % 2;
}
var para = document.getElementById('container').getElementsByTagName('p');
for (var i = 0; i < para.length; i++) {
// for readability
para[i].style.color = 'white';
if (isOdd(i)) {
para[i].style.backgroundColor = 'red';
} else {
para[i].style.backgroundColor = 'black';
}
}
http://jsfiddle.net/Nyuszika7H/8h7RZ/1/embedded/result%2Cjs%2Chtml/
<ul id="mylist">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
<script type="text/javascript">
liArray=document.getElementById('mylist');
for(l=0;l<liArray.length;l++){
if(l%2==1){
liArray[l].style.color='#ff0000';
}
}
</script>
精彩评论