jQuery - Cycle alternate <li>'s?
on the site I am currently developing I'm trying to cycle through a load of <li>
's, but at alternating times. For example:
- To start off with I'd be showing the first two
<li>
items. - Item 1 would fade out.
- Item 3 would fade in, in place of item 1.
- Item 2 would fade out.
- Item 4 would fade in, in pl开发者_开发问答ace of item 2.
HTML:
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
Any idea how I can achieve this effect? Thanks!
You could do something like this (could be simplified further):
$("#items li").slice(2).hide();
var index = false;
setInterval(function() {
$("#items li").eq(index).fadeOut(function() {
$("#items li").eq(2).insertAfter(this).fadeIn();
$(this).appendTo("#items");
index = !index;
});
}, 3000);
This just gives that <ul>
and id to make it faster to work work: <ul id="items">
, you can test it out here. Before you ask, yes I'm blatantly abusing the weak typing to treat index
as both a boolean and a 1
/0
for the .eq()
function.
What this does is:
- Hide any past the first 2
- Start with
false
(0
) index, so we're changing Item 1 first - Every 3 seconds (adjust as you want):
- Fade out the current item, either first or second, alternating
- Take the next in line (currently the 3rd item, 0-based index or
2
for.eq()
) and insert it after where this one just was, fade it in - Take the one that faded out stick it at the end of the line
- Change the index so we change the other one next time
- Repeat in 3 seconds
精彩评论