从您发送的截屏视频中,单击按钮时,此代码应滚动到横幅底部(前提是您正确放置了锚 div):
jQuery(document).ready(function ($) {
// The button is assumed to have an id of 'scroll-down' - triggered when clicked
$('#scroll-down').on('click', function () {
// Move to the pre-defined anchor point
// Insert <div id="scroll-down-anchor"></div> to where you want to scroll to
$('html, body').animate({
scrollTop: $('[id=scroll-down-anchor]').position().top
// Set the speed of the scroll here (currently set to 1000 ms)
}, 1000);
});
});
我仍然不确定从截屏视频中您想根据滚动窗口时的窗口位置来处理行为。
更新:根据截屏视频和更多信息。
代码已经更新,但是,尽管我认为这是您的代码试图实现的目标,但我认为效果根本不是很好,因为您正在拦截用户的意图,劫持它并做出某些事情不同的发生。它也非常不稳定,要改进它可能需要更多的代码行(例如,确定现有滚动的速度,拦截它并使其有机地加速 - 远远超出了这种答案的范围)。也许有一个插件可以很好地做到这一点。
无论如何,我认为这段代码完成了您想要实现的目标,但最终效果虽然是主观的,但在我看来并不是很好。我已经添加了解释性 cmets:
jQuery(document).ready(function ($) {
// Variable to store scrolling state
var scrolling = false;
// Variable to store position to determine whether scrolling up or scrolling down
var previousScroll = 0;
$(window).scroll(function () {
// Only is state is not 'scrolling' (ie not to run if button has been clicked)
if (scrolling === false) {
// Get position
var currentScroll = $(this).scrollTop();
// Compare position to stored variable: scrolling up or scrolling down
if (currentScroll > previousScroll) {
// Determine if position is 'within the zone' - set here to 50px
if (currentScroll < 50 && currentScroll !== 0) {
console.log('IN ZONE');
// Trigger button click
$('#scroll-down').trigger('click');
} else {
// Normal scrolling down code, outside zone
console.log('SCROLLING DOWN ');
}
}
else {
// Scrolling up code
console.log('SCROLLING UP ');
}
// Set variable for comparison of next scroll event
previousScroll = currentScroll;
}
});
// The button is assumed to have an id of 'scroll-down' - triggered when clicked
$('#scroll-down').on('click', function () {
// Set the scrolling state
scrolling = true;
// Animate with callback to set scrolling back to 'true' when complete
$('html, body').animate({ scrollTop: $('[id=scroll-down-anchor]').position().top }, 1000, function () {
// Callback code - set scrolling state to be false when animation has finished
scrolling = false;
});
});
});