[英]smooth scroll an event scroll
我想平滑滾動到錨點,而不是通過單擊來激活,而只是通過事件滾動來激活。
移動滾動條本身將導致滾動條下降到該部分,而向上移動滾動條將使第一部分具有相同的返回效果。
我正在嘗試在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();
}
});
});
該網站的行為符合我的要求,但是由於某些原因,該功能會延遲加載,因此在執行代碼之前它可能會阻塞滾動一秒鍾。 運行代碼的事件是按以下方式檢測觸摸方向: 確定觸摸移動的垂直方向這最好在觸摸屏或移動模式下的開發工具上看到。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.