ant design中锚点Anchor在二级页面中设置滚动偏移量

 版本:
  react: 18.2.0
  antd:5.1.1

 

AnchorPage,tsx

import React, { useEffect, useState } from 'react';
import { Anchor, Row, Col } from 'antd';

const AnchorPage = () => {
  const topRef = React.useRef<HTMLDivElement>(null);
  const [targetOffset, setTargetOffset] = useState<number | undefined>(undefined);

  useEffect(() => {
    setTargetOffset(topRef.current?.clientHeight);
  }, []);
  
  // 指定挂载节点
  const getCont = () => {
    return document.getElementById('LayoutContent') as HTMLElement
  }

  return (
    <div>
      <Row>
        <Col span={18}>
          <div
            id="part-1"
            style={{ height: '100vh', background: 'rgba(255,0,0,0.02)', marginTop: '30vh' }}
          >
            Part 1
          </div>
          <div id="part-2" style={{ height: '100vh', background: 'rgba(0,255,0,0.02)' }}>
            Part 2
          </div>
          <div id="part-3" style={{ height: '100vh', background: 'rgba(0,0,255,0.02)' }}>
            Part 3
          </div>
        </Col>
        <Col span={6}>
          <Anchor
            getContainer={getCont}
            targetOffset={targetOffset}
            items={[
              {
                key: 'part-1',
                href: '#part-1',
                title: 'Part 1',
              },
              {
                key: 'part-2',
                href: '#part-2',
                title: 'Part 2',
              },
              {
                key: 'part-3',
                href: '#part-3',
                title: 'Part 3',
              },
            ]}
          />
        </Col>
      </Row>

      {/* 该元素设置由fixed改为absolute,页面父级元素设置为relative */}
      <div
        style={{
          height: '30vh',
          background: 'rgba(0,0,0,0.85)',
          position: 'absolute',
          top: '10px', 
          left: '10px',
          // 宽度根据页面自定义增或减,此处为左右15共30px
          width: 'calc(75% - 30px)',
          color: '#FFF',
        }}
        ref={topRef}
      >
        <div>Fixed Top Block</div>
      </div>
    </div>
  );
};

export default AnchorPage;

 

官方为,父元素为整个window

 

posted @ 2023-01-03 10:31  王希有  阅读(1213)  评论(0编辑  收藏  举报