如何为自动滚动网页设置动画?

时间:2019-02-08 12:48:45

标签: jquery

我目前有一个具有无限滚动div的网页 https://codepen.io/anon/pen/ZwvgVg

我正在尝试使div动画以在页面加载时自动以固定页面或固定文本无限滚动

有人有什么建议吗?

var divs = ['#top', '#middle', '#center', '#bottom'];

var current = '#top';
var next = '#center';

$('#body').on('DOMMouseScroll mousewheel', function (e) {

    if(e.originalEvent.detail > 0 || e.originalEvent.wheelDelta < 0 ) {
        // Scrolling down
        if(!inScreen(current) && inScreen(next)) {
            $('#body').append($(current));
            current = divs[getNextIndex(current)];
              next = divs[getNextIndex(next)];
        }
    } else { // Scrolling up
        if(!inScreen(divs[getNextIndex(current)]) && inScreen(current)) {
          $('#body').prepend($(divs[getPrevIndex(current)]));
          current = divs[getPrevIndex(current)];
        }
    }
});

 //  Function to check if element is in view port
 var inScreen = function (elem) {
     let elem_top = $(elem).offset().top;
     let elem_bottom = elem_top + $(elem).outerHeight();
     let window_top = $(window).scrollTop();
     let window_bottom = window_top + $(window).height();

    return elem_bottom > window_top && elem_top < window_bottom;
};

// Function to get next index if last index then get the first one
var getNextIndex = function (item) {
    let idx = divs.findIndex(divs => divs === item);

    if((divs.length - 1) == idx) {
        idx = 0;
    } else {
        idx++;
    }

    return idx;
}

// Function to get previous index if first index then get the last one
var getPrevIndex = function (item) {
    let idx = divs.findIndex(divs => divs === item);

    if(0 == idx) {
        idx = divs.length - 1;
    } else {
        idx--;
    }
    return idx;
}

0 个答案:

没有答案