我想平滑滚动到 anchor ,它不是通过单击激活的,而是通过事件滚动激活的。
移动滚动条本身将导致滚动条向下移动到该部分,向上移动滚动条将对第一部分产生相同的返回效果。
我正尝试在 jQuery 中执行此操作,但我错过了一些东西。我设法下拉到底部,但功能阻止了我。当然有一些简单的提示,但我不知道要寻找什么。
function transitionScroll() {
if ($(window).width() <= 767) {
let scrollWatch = window.pageYOffset;
let positionOfElement = $("#small-carousel").offset().top;
if ((scrollWatch <= positionOfElement) && (scrollWatch != 0)) {
$([document.documentElement, document.body]).animate({ scrollTop: $("#small-carousel").offset().top }, 1000);
}
}
$(window).resize(function () {
if ($(window).width() <= 767) {
let scrollWatch = window.pageYOffset;
let positionOfElement = $("#small-carousel").offset().top;
if (scrollWatch <= positionOfElement) {
$([document.documentElement, document.body]).animate({ scrollTop: $("#small-carousel").offset().top }, 1000);
}
}
});
};
transitionScroll();
window.addEventListener('scroll', transitionScroll);
最佳答案
最后,我写了一个工作代码。
https://codepen.io/toMuchMike/pen/JVWppq?editors=0011
let windowOnSecond = false;
let touchStart;
const positionOfFirst = $(".first-section").offset().top;
const positionOfSecond = $(".second-section").offset().top;
$(document).ready(function () {
function doScrolling() {
$(document).on('touchstart', function (e) {
touchStart = e.originalEvent.touches[0].clientY;
});
$(document).on('touchend', function (e) {
var touchEnd = e.originalEvent.changedTouches[0].clientY;
if (touchStart > touchEnd + 5) {
let scrollPosition = window.pageYOffset;
//slide_down
if ((scrollPosition = positionOfFirst) && (windowOnSecond === false)) {
$("html, body").animate({ scrollTop: $(".second-section").offset().top }, 1000);
windowOnSecond = true;
console.log("DOWN");
}
} else if (touchStart < touchEnd - 5) {
let scrollPosition = window.pageYOffset;
//slide_up
if (scrollPosition <= positionOfSecond) {
$("html, body").animate({ scrollTop: $(".first-section").offset().top }, 1000);
windowOnSecond = false;
console.log("UP");
}
}
});
};
if ($(window).width() <= 767) {
doScrolling();
}
$(window).resize(function () {
if ($(window).width() <= 767) {
doScrolling();
}
});
});
该网站的行为符合我的要求,但由于某种原因,该功能会延迟加载,它可能会在代码执行前阻止滚动一秒钟。 运行代码的事件是检测触摸方向,如下所示:Determine vertical direction of a touchmove这最好在触摸屏或移动模式下的开发工具上看到。
关于javascript - 平滑滚动事件滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55619357/