Плавный скролинг по секциям на чистом javascript

103
22 сентября 2019, 01:10

На сайте нужно реализовать плавную прокрутку по секциям на чистом 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; 
}
<header></header> 
<main> 
  <section> 
    <div class="item"></div> 
    <div class="item"></div> 
    <div class="item"></div> 
  </section> 
  <section></section> 
</main> 
<footer></footer>

Как видно, прокрутка работает криво, не пойми как, хотелось бы, чтобы она была плавная и по секциям, никак не получается додумать скрипт. Прошу помощи.

Answer 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; 
}
<header></header> 
<main> 
  <section id="first"> 
    <div class="item"></div> 
    <div class="item"></div> 
    <div class="item"></div> 
  </section> 
  <section id="second"></section> 
</main> 
<footer></footer>

А это для секций, которых > 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; 
}
<header></header> 
<main> 
  <section id="first"> 
    <div class="item"></div> 
    <div class="item"></div> 
    <div class="item"></div> 
  </section> 
  <section id="second"></section> 
  <section id="third"></section> 
  <section id="fourth"></section> 
</main> 
<footer></footer>

READ ALSO
Смена языков для приложения Vue.js

Смена языков для приложения Vue.js

у меня есть небольшое SPA приложение на Vuejs

71
как добавить кавычки в innerHTML

как добавить кавычки в innerHTML

как сделать ,чтобы на странице отображалось "rJokevalue" ? А не просто rJoke

126
дёргается навбар при прокрутке

дёргается навбар при прокрутке

есть страница с навбаром, который с помощью JS уменьшается при прокрутке вниз, при этом всегда оставаясь вверху (position: sticky)если быстро и сильно...

80
Переход на gulp 4 версии,

Переход на gulp 4 версии,

Смотрю курс по верстке html письма и видимо после обновления gulp стала вылетать ошибка, как мне её исправить, я уже читал документацию, смотрел...

106