#javascript #анимация #scroll
На сайте нужно реализовать плавную прокрутку по секциям на чистом javascript, без
всяких плагинов и библиотек.
Есть код:
var height = document.querySelector("section").clientHeight;
(function() {
var supportOffset = window.pageYOffset !== undefined,
lastKnownPos = 0,
ticking = false,
scrollDir;
function doSomething(scrollPos, scrollDir) {
if (scrollDir === 'down') {
window.scrollBy(0, height);
}
console.log('scroll pos: ' + scrollPos + ' | scroll dir: ' + scrollDir);
}
window.addEventListener('wheel', function(e) {
currYPos = supportOffset ? window.pageYOffset : document.body.scrollTop;
scrollDir = lastKnownPos > currYPos ? 'up' : 'down';
lastKnownPos = currYPos;
if (!ticking) {
window.requestAnimationFrame(function() {
doSomething(lastKnownPos, scrollDir);
ticking = false;
});
}
ticking = true;
});
})();
* {
padding: 0;
margin: 0;
}
section {
height: 100vh;
background-color: pink;
display: flex;
flex-wrap: wrap;
}
section:last-child {
background-color: green;
}
.item {
width: 33.1605%;
background-color: #f3f3f3;
margin: 1px;
}
Как видно, прокрутка работает криво, не пойми как, хотелось бы, чтобы она была плавная
и по секциям, никак не получается додумать скрипт. Прошу помощи.
Ответы
Ответ 1
Краткость - сестра таланта))) window.addEventListener('wheel', function(e) { e.preventDefault(); if (e.deltaY < 0) scrollToSection('first'); else scrollToSection('second'); }); function scrollToSection(id) { document.getElementById(id).scrollIntoView({ behavior: 'smooth' }); } * { padding: 0; margin: 0; } section { height: 100vh; background-color: pink; display: flex; flex-wrap: wrap; } section:last-child { background-color: green; } .item { width: 33.1605%; background-color: #f3f3f3; margin: 1px; }А это для секций, которых > 2 const sections = [...document.getElementsByTagName('section')]; let currentSection = 0; window.addEventListener('wheel', function(e) { e.preventDefault(); (e.deltaY < 0) ? --currentSection: ++currentSection; if (currentSection < 0) currentSection = 0; else if (currentSection > (sections.length - 1)) currentSection = (sections.length - 1); scrollToSection(currentSection); }); function scrollToSection(i) { document.getElementById(sections[i].id).scrollIntoView({ behavior: 'smooth' }); } * { padding: 0; margin: 0; } section { height: 100vh; background-color: pink; display: flex; flex-wrap: wrap; } section:nth-child(2) { background-color: green; } section:nth-child(3) { background-color: red; } section:last-child { background-color: blue; } .item { width: 33.1605%; background-color: #f3f3f3; margin: 1px; }
Комментариев нет:
Отправить комментарий