scrollIntoView()가 컨테이너를 페이지 상단으로 스크롤하는 것을 방지합니다.
P粉690200856
P粉690200856 2024-03-26 20:25:28
0
1
417

스크롤 스냅을 사용하지만 현재 표시된 슬라이드를 제어하기 위한 탐색 버튼도 포함하는 간단한 "주로 CSS" 이미지 캐러셀을 만들려고 합니다. 내가 찾은 유일한 해결책은 내가 원하는 작업을 수행하는 대상 요소에 scrollIntoView()를 사용하는 것입니다. 그러나 이 방법은 항상 대상 요소를 페이지 상단으로 스크롤합니다. 대상 캐러셀 슬라이드와 컨테이너를 원래 위치에 유지하고 슬라이드가 가로로 스크롤되어 표시되기를 원합니다. 저는 Adam Argyle의 예를 보고 있었는데 그는 그렇게 했고 컨테이너는 원래 위치에 그대로 있었습니다. 그의 시연에서 무엇이 다른지 모르겠습니다.

시연을 위해 코드펜을 만들었습니다.

https://codepen.io/krjo-the-decoder/pen/dyjPrLy

하단의 숫자 버튼을 클릭하면 오른쪽 슬라이드로 올바르게 스크롤되며 페이지 전체 컨테이너도 스크롤됩니다.

컨테이너의 y축 스크롤을 기존 위치로 설정하기 위해 scrollIntoView() 전후에 scrollTo()를 사용해 보았지만 아무런 효과가 없었습니다.

<!-- Using tailwind.css -->
<div class="py-48 bg-gray-200">
  <h1 class="text-center font-bold mb-5 text-2xl">Scroll-snap Carousel</h1>
  <div class="grid grid-flow-col overflow-x-auto snap-x snap-mandatory overscroll-x-contain auto-cols-[100%] mx-auto w-[500px]">
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
    <img src="https://via.placeholder.com/500" width="500" height="500" class="block snap-center w-auto h-auto" data-slide>
  </div>
  <nav class="flex justify-center mt-4">
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="0">1</button>
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="1">2</button>
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="2">3</button>
    <button class="p-2 border rounded-full border-solid border-black w-12 h-12 mx-2" type="button" data-index="3">4</button>
  </nav>
</div>

<script>
const slides = document.querySelectorAll('[data-slide]');
document.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', event => {
    console.log('event',event);
    slides[event.target.dataset.index].scrollIntoView({
      behavior: 'smooth',
      inline:   'center',
    });
  });
});
</script>

P粉690200856
P粉690200856

모든 응답(1)
P粉976737101

다음과 같이 scrollIntoView 옵션에 block: 'nearest'를 추가해 보세요.

으아아아
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!