0

因此,我为我的投资组合网站编写了一个脚本,以按索引滚动到部分。它适用于所有经过测试的浏览器和智能手机,但在 mac 设备上它可能不起作用,而是滚动到下一部分,它会自动转到下一部分。

希望有人可以帮助我。

var anchorPoints = [];
var anchorLocation = [];
var anchorIndex = 0;
var waiting = false;
var canScroll = true;
var offset = 0

window.onload = function () {
    anchorPoints = document.getElementsByClassName("js-anchor");

    for (i = 0; i < anchorPoints.length; i++) {
        getLocation = anchorPoints[i].getBoundingClientRect();
        getLocation = getLocation.top - offset;

        anchorLocation.push(parseInt(getLocation));
    }
}

$(document).on('mousewheel DOMMouseScroll', function (e) {
    if (detectMobile() == true) {
        return;
    }
    if ((waiting || canScroll == false)) {
        return;
    }
    e.preventDefault();//prevent the default mousewheel scrolling
    var active = $('section.active');
    var delta = e.originalEvent.detail < 0 || e.originalEvent.wheelDelta > 0 ? 1 : -1;
    waiting = true;
    if (delta < 0) {
        anchorIndex += 1;
        if (anchorIndex > (anchorPoints.length - 1)) {
            anchorIndex = 0;
        } 
        scrollTo({
            top: anchorLocation[anchorIndex],
            left: 0,
            behavior: 'smooth'
        });

        console.log(anchorIndex);
        console.log('scrolling down');
    } else {
        anchorIndex -= 1;
        if (anchorIndex < 0) {
            anchorIndex = anchorPoints.length - 1;

        }
        scrollTo({
            top: anchorLocation[anchorIndex],
            left: 0,
            behavior: 'smooth'
        });
        console.log(anchorIndex);
        console.log('scrolling up');
    }
    setTimeout(function () {
        waiting = false;
    }, 1000);
});
4

0 回答 0