我已经摸索了两个小时,试图找出要滚动的算法,以便所选项目位于中间。

所以我有几个变量,我不知道该怎么办
基本上我有一个播放列表,您可以通过在键盘上上下移动来选择要播放的歌曲
和轨道改变,每次改变我都需要滚动

这是我的变量:

var playlistContainer = $('.playlist').height(); // playlist container with overflow auto - 400px;
var listItemHeight    = $('.item:first').outerHeight(); // getting a list item height. - 30px;
var currentItemScrollTop = $('.item_current').position().top; // the current item scroll position.
var listLength  = $('li').length;

$('.playlist').animate({
  scrollTop: // have no idea what the algorithm is - i need the '.item_current' to be in the middle when possible.
}, 'slow');


提前致谢。

最佳答案

- - - - - 更新后的版本 - - - - -

http://jsfiddle.net/pixelass/VVVR4/8/

$(window).keydown(function(e) {
    if (e.keyCode == 40) {
        fromTop = $('.selected').position().top;
        if (!$('.playlist li:last-child').hasClass('selected')) {
            if (fromTop >= 160) {
                $('.playlist').animate({
                    scrollTop: '+=32px'
                }, 200);
            }
            $('.selected').removeClass('selected').next().addClass('selected');
        }
        return false;
    } else if (e.keyCode == 38) {
        fromTop = $('.selected').position().top;
        if (!$('.playlist li:first-child').hasClass('selected')) {
            if (fromTop <= 160) {
                $('.playlist').animate({
                    scrollTop: '-=32px'
                }, 200);
            }
            $('.selected').removeClass('selected').prev().addClass('selected');
        }
        return false;
    }
});

关于jquery - 我如何计算我需要滚动多少,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8561141/

10-10 23:17