自动完成滚动

时间:2014-04-04 09:16:56

标签: javascript jquery html css

我有一个这样的列表:http://jsfiddle.net/Vtn5Y/559/

var li = $('li');
var liSelected;
$(window).keydown(function(e){
    if(e.which === 40){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.eq(0).addClass('selected');
            }
        }else{
            liSelected = li.eq(0).addClass('selected');
        }
    }else if(e.which === 38){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.last().addClass('selected');
            }
        }else{
            liSelected = li.last().addClass('selected');
        }
    }
});

现在我想知道如何让div向下滚动以便能够看到所选项目。

谢谢!

2 个答案:

答案 0 :(得分:2)

这里有一个类似的问题:How to scroll to specific item using jQuery?

解决方案是使用scrollTop属性,如下所示:

var container = $('div'),
scrollTo = $('#row_8');

container.scrollTop(
    scrollTo.offset().top - container.offset().top + container.scrollTop()
);

// Or you can animate the scrolling:
container.animate({
    scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
});​

工作示例:http://jsfiddle.net/xY7tx/406/

答案 1 :(得分:1)

抱歉,我的第一个回答出了问题。

试试这个:

var li = $('li');
var liSelected;
$(window).keydown(function(e){
    if(e.which === 40){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.eq(0).addClass('selected');
            }
        }else{
            liSelected = li.eq(0).addClass('selected');
        }
    }else if(e.which === 38){
        if(liSelected){
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0){
                liSelected = next.addClass('selected');
            }else{
                liSelected = li.last().addClass('selected');
            }
        }else{
            liSelected = li.last().addClass('selected');
        }
    }
    $('div').scrollTop(liSelected.position().top - $('div').position().top + $('div').scrollTop());
});

JSFidle here