>  기사  >  웹 프론트엔드  >  사용자 스크롤링 애플리케이션 기반 CSS 구현(코드)

사용자 스크롤링 애플리케이션 기반 CSS 구현(코드)

不言
不言앞으로
2019-03-30 11:38:551772검색

이 글의 내용은 사용자 기반 스크롤링 애플리케이션(코드)의 CSS 구현에 관한 것입니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

현재 스크롤 오프셋을 html 요소의 속성에 매핑하면 현재 스크롤 위치를 기반으로 페이지의 요소 스타일을 지정할 수 있습니다. 이를 사용하여 부동 탐색 구성요소를 구축할 수 있습니다.

이것은 우리가 사용할 HTML이며, 아래로 스크롤할 때 콘텐츠 위에 뜨고 싶은 멋진 구성 요소인

<header>I'm the page header</header>
<p>Lot's of content here...</p>
<p>More beautiful content...</p>
<p>Content...</p>

먼저 'scroll' 이벤트, document 및 scrollY를 수신하고 사용자가 스크롤할 때마다 현재 위치를 요청합니다.

document.addEventListener('scroll', () => {
  document.documentElement.dataset.scroll = window.scrollY;
});

html 요소의 데이터 속성에 스크롤 위치를 저장합니다. 개발 도구를 사용하여 DOM을 보면 다음과 같습니다.

<html data-scroll="0">

이제 이 속성을 사용하여 페이지의 요소 스타일을 지정할 수 있습니다.

/* Make sure the header is always at least 3em high */
header {
  min-height: 3em;
  width: 100%;
  background-color: #fff;
}

/* Reserve the same height at the top of the page as the header min-height */
html:not([data-scroll='0']) body {
  padding-top: 3em;
}

/* Switch to fixed positioning, and stick the header to the top of the page */
html:not([data-scroll='0']) header {
  position: fixed;
  top: 0;
  z-index: 1;

  /* This box-shadow will help sell the floating effect */
  box-shadow: 0 0 .5em rgba(0, 0, 0, .5);
}

기본적으로 아래로 스크롤하면 이제 제목이 페이지에서 자동으로 분리되어 콘텐츠 위에 떠 있게 됩니다. JavaScript 코드는 이에 대해 신경 쓰지 않으며 해당 작업은 데이터 속성에 스크롤 오프셋을 넣는 것입니다. 이는 JavaScript와 CSS 사이에 긴밀한 결합이 없기 때문에 좋습니다.

주로 성능 부분에서는 여전히 일부 개선 사항이 있습니다.

하지만 먼저 페이지가 로드될 때 스크롤 위치가 맨 위에 있지 않도록 스크립트를 수정해야 합니다. 이러한 경우 제목이 잘못 렌더링됩니다.

페이지가 로드되면 현재 스크롤 오프셋을 빠르게 가져와야 합니다. 이를 통해 우리는 항상 현재 상황과 동기화됩니다.

// Reads out the scroll position and stores it in the data attribute
// so we can use it in our stylesheets
const storeScroll = () => {
  document.documentElement.dataset.scroll = window.scrollY;
}

// Listen for new scroll events
document.addEventListener('scroll', storeScroll);

// Update scroll position for first time
storeScroll();

다음으로 몇 가지 성능 개선 사항을 살펴보겠습니다. 해당 scrollY 위치를 요청하면 브라우저는 올바른 위치를 반환하는지 확인하기 위해 페이지에 있는 모든 요소의 위치를 ​​계산해야 합니다. 모든 스크롤 상호 작용에서 이 작업을 수행하도록 강제하지 않는 것이 가장 좋습니다.

이를 위해서는 디바운스(debounce) 방법이 필요합니다. 이 방법은 브라우저가 다음 프레임을 그릴 준비가 될 때까지 요청을 대기열에 넣습니다. 이 시점에서 페이지에 있는 모든 요소의 위치를 ​​계산하므로 다음 프레임을 그릴 수 없습니다. 다시.

// The debounce function receives our function as a parameter
const debounce = (fn) => {

  // This holds the requestAnimationFrame reference, so we can cancel it if we wish
  let frame;

  // The debounce function returns a new function that can receive a variable number of arguments
  return (...params) => {
    
    // If the frame variable has been defined, clear it now, and queue for next frame
    if (frame) { 
      cancelAnimationFrame(frame);
    }

    // Queue our function call for the next frame
    frame = requestAnimationFrame(() => {
      
      // Call our function and pass any params we received
      fn(...params);
    });

  } 
};

// Reads out the scroll position and stores it in the data attribute
// so we can use it in our stylesheets
const storeScroll = () => {
  document.documentElement.dataset.scroll = window.scrollY;
}

// Listen for new scroll events, here we debounce our `storeScroll` function
document.addEventListener('scroll', debounce(storeScroll));

// Update scroll position for first time
storeScroll();

이벤트를 수동적으로 표시함으로써 스크롤 이벤트가 터치 상호작용(예: Google 지도와 같은 플러그인과 상호작용할 때)으로 취소되지 않음을 브라우저에 알릴 수 있습니다. 이를 통해 브라우저는 이벤트가 취소되지 않을 것임을 알기 때문에 즉시 페이지를 스크롤할 수 있습니다.

document.addEventListener('scroll', debounce(storeScroll), { passive: true });

이 기사는 여기서 끝났습니다. 더 흥미로운 콘텐츠를 보려면 PHP 중국어 웹사이트의 CSS Video Tutorial 칼럼을 주목하세요!

위 내용은 사용자 스크롤링 애플리케이션 기반 CSS 구현(코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 segmentfault.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제