停止滚动到每个点击的 link,只滚动到第一个点击的 link

Stop scrolling to every clicked link one after one, scroll just to the first clicked link

我需要修复我的代码。如果我在菜单中单击多个 html href link,我的脚本将滚动到每个单击的 link 一个接一个 link 。我只需要滚动到第一个单击的 link,而在滚动功能期间另一个单击的 link 将被忽略。

jQuery(window).bind("load", function () {
var hash = window.location.hash;

hash = hash.replace("#", "");

var elem = jQuery(".pb-line-css-group-" + hash);

menu_scroll_to(elem);
});

jQuery(document).ready(function () {

jQuery(".menu-item A").click(function () {
    var hash = jQuery(this).attr('href');

    hash = hash.replace("#", "");
    hash = hash.replace("/", "");

    var elem = jQuery(".pb-line-css-group-" + hash);

    menu_scroll_to(elem);
});
});

function menu_scroll_to(elem) {

if (elem) {
    jQuery('html, body').animate({
        scrollTop: elem.offset().top - 70
    }, 2000, "easeOutQuint");
}

}

您可以设置一个去抖功能,这样您在一段时间内多次点击时只调用 menu_scroll_to() 一次。

这里是一个 link 去抖功能,应该可以工作。

Debounce function

将该函数添加到您的 JS 并替换以下行:

menu_scroll_to(elem);

与:

debounce(function() {
    menu_scroll_to(elem);
}, 250);

其中 250 是以毫秒为单位的时间。

最终的代码应该是这样的:

jQuery(window).bind("load", function () {
        var hash = window.location.hash;

        hash = hash.replace("#", "");

        var elem = jQuery(".pb-line-css-group-" + hash);

        menu_scroll_to(elem);
});

jQuery(document).ready(function () {

        jQuery(".menu-item A").click(function () {
                var hash = jQuery(this).attr('href');

                hash = hash.replace("#", "");
                hash = hash.replace("/", "");

                var elem = jQuery(".pb-line-css-group-" + hash);

                debounce(function () {
                    menu_scroll_to(elem);
                }, 250);
        });
});

function menu_scroll_to(elem) {
    if (elem) {
            jQuery('html, body').animate({
                    scrollTop: elem.offset().top - 70
            }, 2000, "easeOutQuint");
    }
};

function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};