我的网站有两个滚动选项。向下滚动时,它会滚动到锚点1。
我还有一个跳转到相同锚点的按钮。
我的问题:当我点击按钮时,网站会跳转到锚点,但由于锚点有两种方法,它也会触发第一个滚动选项。
jQuery(document).ready(function($) {
var flag = true;
$(window).scroll(function () {
if (flag == true) {
scroll = $(window).scrollTop();
if (scroll > 50) $('#scroll-down')[0].click();
flag = false;
}
});
$(window).scroll(function () {
if (flag == false) {
scroll = $(window).scrollTop();
if (scroll < 50 )
flag = true;
}
});
});
任何解决方案吗?
答案 0 :(得分:0)
在您发送的截屏视频中,此代码应在单击按钮时滚动到横幅的底部(假设您正确放置了锚点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);
});
});
我仍然不确定在截屏时你想要在窗口滚动时基于窗口位置的行为做什么。
更新:根据截屏视频和更多信息。 代码已经更新,但是,我认为,这是你的代码试图实现的目标,我认为效果不是很好,因为你正在拦截用户的意图,劫持它,并制作一些东西不同的事情。它也非常不稳定,并且为了改进它可能需要更多代码行(例如,确定现有滚动的速度,拦截它并使其有机加速 - 超出这种答案的范围)。也许有一个插件可以很好地完成这个。
无论如何,我认为这段代码完成了你想要实现的目标,但最终效果虽然是主观的,但在我看来并不是很好。我已经提出了解释性意见:
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;
});
});
});