我需要修复我的代码。如果我单击菜单中的多个 html href 链接,我的脚本将一一滚动到每个单击的链接。我需要滚动到第一个单击的链接,并且滚动功能期间另一个单击的链接将被忽略。
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() 。
这里是一个应该可以工作的去抖函数的链接。
将该函数添加到您的 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);
};
};
关于javascript - 停止逐个滚动到每个单击的链接,仅滚动到第一个单击的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28728921/