问题描述:

On page load I want to highlight a menu item and unhighlight it again after a second. I want to accomplish sort of a Knight Rider effect but only in one direction. From left to right and it should stop when it has traversed all the menu items. This way I want to put more attention on my menu bar.

My HTML:

<div id="header">

<ul class="menu">

<li class="menu-item"><a class="menu-item-link">Stage1</a></li>

<li class="menu-item"><a class="menu-item-link">Stage2</a></li>

</ul>

</div>

My CSS:

.highlight { color: #FFFFFF; }

$(document).ready(function () {

$(".menu-item a").each(function () {

$(this).addClass('highlight').delay(1000).removeClass('highlight');

});

});

I have tried the below suggestions but it didn't work.

网友答案:

You might want to try a recursive / callback pattern to add the next element's class as soon as the previous one gets removed.

var runner = function (el) {

    var next = el.addClass('highlight').next('.menu-item a');

    setTimeout(function () {
        el.removeClass('highlight');
        next && runner(next);
    }, 1000)        
};

runner($('.menu-item a:first'));

Untested code though. I'll see if I can whip up a jsFiddle in a while.

EDIT

Here you go.

EDIT 2

... and that's the reason why you also post the relevant HTML code.

So, considering HTML like:

<div id="header">
    <ul class="menu">
        <li class="menu-item"><a class="menu-item-link">Stage1</a></li>
        <li class="menu-item"><a class="menu-item-link">Stage2</a></li> 
    </ul>
</div>

use this instead:

var items = $('.menu-item a'),
    runner = function (el) {

        var next = items.eq(items.index(el) + 1).addClass('highlight');

        setTimeout(function () {
            el.removeClass('highlight');
            !!next.length && runner(next);
        }, 1000);
    };

runner(items.first());
网友答案:
$(document).ready(function () {
  $(".menu-item a").each(function () {
    $(this).addClass("error").delay(1000).queue(function(next){
    $(this).removeClass("error");
   next();
  });
});
相关阅读:
Top