开发者

How to select all li greater than that the cursor hover it?

I want to change css color of all li elements that greater than that the cursor I hover. To be clear I give an example: Suppose I have 10 li - elements in an unordered-list (ul - element).When I hover o开发者_C百科ver 5th element I want that all elements from 5 to 10 will be changed css color (first 4 elements remains black be default). My code is this one, but it doesn't work:

$(function(){
            $("li").hover(
                 function () {                   
                    var l = $("li").index(this);
                    $('div').html(l);
                    $("li:gt(l)").css('color','red');                    
                 }, 
                 function () {
                    $('div').html("");
                    $('li').css('color','black');
                 }
            );
});


you almost got that right, the problem is that you have to use the actual Value of the l variable in the selector, like that:

$(function(){

            $("li").hover(
                 function () {                   
                    var l = $("li").index(this);
                    $('div').html(l);
                    $("li:gt(" + l + ")").css('color','red');                    
                 }, 
                 function () {
                    $('div').html("");
                    $('li').css('color','black');
                 }
            );
});


Use nextAll():

$(function(){
        $("li").hover(
             function () {                   
                var l = $("li").index(this);
                $('div').html(l);
                $(this).nextAll('li').andSelf().css('color','red');                    
             }, 
             function () {
                $('div').html("");
                $('li').css('color','black');
             }
        );
});


And I founded one more posibility with slice():

$(function(){
            $("li").hover(
             function () {                   
                var l = $("li").index(this);
                $('div').html(l);
                $('li').slice(l).css('color', 'red');                    
             }, 
             function () {
                $('div').html("");
                $('li').css('color','black');
             }
        );
        });   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜