Horizontal Scrolling of web page

HYl·2022년 4월 3일
3

Introduction

수평 스크롤 효과를 구현하고 있으며, 사용자가 일반적으로 수직으로 스크롤을 해도 페이지가 수평으로 스크롤 된다.

Setting up the HTML

<body>

  <div style="height: 100vh; width: 100vw;" class="br"></div> <!--Just extra div for scrolling space-->

  <div class="sticky-parent">
    <div class="sticky">
      <div class="horizontal"> <!--Horizantal conatiner with display flex-->

        <!--Content Start-->
        <div class="dim" style="background-color: aqua;"></div>
        <div class="dim" style="background-color: rgb(255, 238, 0);"></div>
        <div class="dim" style="background-color: rgb(81, 255, 0);"></div>
        <div class="dim" style="background-color: rgb(247, 0, 255);"></div>
        <div class="dim" style="background-color: rgb(27, 24, 179);"></div>
        <div class="dim" style="background-color:black"></div>
        <!--Content End-->

      </div>
    </div>
  </div>
  <div style="height: 100vh; width: 100vw;""></div> <!--Extra Scroll Space-->
  <script src="/javascript.js" ></script>
</body>

Setting up CSS

주의해야 할 사항은, 사용자가 어떤 화면을 사용할지 알 수 없기 때문에 픽셀을 사용한 고정적인 사이즈 대신에 vw vh 라는 상대 단위를 사용한다.

.sticky-parent{
  height: 700vh;
}

.sticky{
  position: sticky;
  top: 0px;
  max-height: 100vh;
  overflow-x: hidden;
  overflow-y: hidden;
}

.horizontal{
  display: flex;
}

Adding JavaScript to enable Horizontal Scroll


"use strict"

// Adding scroll event listener
document.addEventListener('scroll', horizontalScroll);

//Selecting Elements
let sticky = document.querySelector('.sticky');
let stickyParent = document.querySelector('.sticky-parent');

// 수평 폭에 매핑해야 하는 실제 스크롤 높이를 찾으려면, stickyparent의 높이 - sticky의 높이
let scrollWidth = sticky.scrollWidth;
let verticalScrollHeight = stickyParent.getBoundingClientRect().height-sticky.getBoundingClientRect().height;

//Scroll function 
function horizontalScroll(){

    //Checking whether the sticky element has entered into view or not
    let stickyPosition = sticky.getBoundingClientRect().top;
    if(stickyPosition > 1){
        return;
    }else{
        let scrolled = stickyParent.getBoundingClientRect().top; //how much is scrolled?
        sticky.scrollLeft = (scrollWidth / verticalScrollHeight) * (-scrolled) * 0.85;
    
    }
}
  • scrollWidth : scroll 되는 부분을 포함한 실제 요소의 너비값이다.
  • scrollLeft : 스크롤 바 수평 위치 / MDN

결과


REFERENCE

https://carberi.pp.ua/horizontal-scrolling-of-web-page-with-vanilla-javascript/#introduction

profile
꾸준히 새로운 것을 알아가는 것을 좋아합니다.

0개의 댓글