1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

画面中央のコンテンツだけスクロールできるようにしたい

Last updated at Posted at 2024-07-01

はじめに

このような動きを作ります。

Animation.gif

以下のサイトからWebデザインのレイアウトを探していたところ、

こちらのサイトに目が留まりましたので真似てみました。

やりたいこと

  • 中央コンテンツをスクロールできる
  • 中央コンテンツをスクロールしても左右コンテンツはスクロールされない
  • 左右コンテンツのボタンをクリックすると該当箇所にジャンプできる

コード

App.tsx
import React, { useRef } from 'react';
import { Box, Button, Container, Flex, VStack } from '@chakra-ui/react';
import { Content1 } from './pages/Content1';
import { Content2 } from './pages/Content2';
import { Content3 } from './pages/Content3';

function App() {
 const contentRef1 = useRef<HTMLDivElement>(null);
 const contentRef2 = useRef<HTMLDivElement>(null);
 const contentRef3 = useRef<HTMLDivElement>(null);

 const handleScrollToContent = (ref: React.RefObject<HTMLDivElement>) => {
    ref.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
 };

 return (
    <>
    <Flex direction="row" h="100vh" overflowY='scroll'>

      <Container w="50%" h="100vh" position="relative" zIndex="20" >
        <Box width="500px" h="100vh" ref={contentRef1}><Content1></Content1></Box>
        <Box width="500px"  h="100vh" ref={contentRef2}><Content2></Content2></Box>
        <Box width="500px"  h="100vh" ref={contentRef3}><Content3></Content3></Box>
      </Container>

      <VStack spacing={4} w="50%" position="fixed" right="0" top="50%" zIndex="30">
        <Button onClick={() => handleScrollToContent(contentRef1)}>中央コンテンツ1へ</Button>
        <Button onClick={() => handleScrollToContent(contentRef2)}>中央コンテンツ2へ</Button>
        <Button onClick={() => handleScrollToContent(contentRef3)}>中央コンテンツ3へ</Button>
      </VStack>
    </Flex>
    </>
 );
}

export default App;

ポイント

  • レイヤー構造をつくる
    左右コンテンツのz-indexを高くすることで、スクロール時の画面の動きを中央コンテンツと切り離すことができます。

おわりに

Webデザインのレイアウト集は眺めているだけでも面白いですね。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?