简体   繁体   中英

Newbie help with Jquery code - I need to stop the last list element from fading out

This has now been answered (thanks to all you guys)

I want to prevent the last list element from fading out I am in my first week with jquery and have been trying all sorts of different stategies with no success. All the code I find seems to want to loop through all the elements recursively, which I do not want. I want the code to end at the last item without the last list element fading out. I am aware of all the cycle plug-ins but I just want basic functionality.

Thanks for you help, hope I have not broke any rules, it is my first question.

I feel a bit stupid now, I orginally forgot to add my css and also failed to mention I wanted each list element to fadeIn over the previous list element, hence the position absolute. The 3 solutions that have been submitted worked wonderfully but I asked the wrong thing, it was just me that did not explain things properly, my apologies. Any futher help would be much appreciated.

The CSS I forgot first time around
#container ul li {
position:absolute;
display:none;
}     
<script type="text/javascript">

$(document).ready(function() {

(function hidenext(jq){
    jq.eq(0).fadeIn(1000).delay(5000).fadeOut(1000, function(){
        (jq=jq.slice(1)).length && hidenext(jq);
    });
})($('div#container ul li'))

});

</script>


<div id="container">


      <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
      </ul>

</div>

Try this

$(document).ready(function() {

(function hidenext(jq){
    jq.eq(0).fadeIn(1000).delay(5000).fadeOut(1000, function(){
        (jq=jq.slice(1)).length && hidenext(jq);
    });
})($('div#container ul li:not(:last)'))

});

You just need to add > 1 to the stop condition. So, change from

(jq=jq.slice(1)).length

to

(jq=jq.slice(1)).length > 1

Demo

Try this ;)

$('div#container ul li').not(':last').each(function(idx, elt) {
    idx++;
    $(elt).fadeIn(idx * 1000).delay(idx * 5000).fadeOut(idx * 1000);
});

http://jsfiddle.net/dzRsp/

EDIT Something like that should be better :

$('div#container ul li').not(':last').each(function(idx, elt) {
    idx++;
    if (idx > 1)
        $(elt).delay(idx * 3000);
    $(elt).fadeIn(idx * 1000).delay(idx * 5000).fadeOut(idx * 1000, function() {
        if (idx + 1 == $('div#container ul li').size())
            $('div#container ul li:last').fadeIn(1000);
    });
});

http://jsfiddle.net/dzRsp/1/

If you have more than 3 elements it bugs, but I wanted to give you the idea :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM