首页 > 其他分享 >ant design中锚点Anchor在二级页面中设置滚动偏移量

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

时间:2023-01-03 10:47:06浏览次数:40  
标签:const Part href 偏移量 ant part design targetOffset 页面

 版本:
  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

 

标签:const,Part,href,偏移量,ant,part,design,targetOffset,页面
From: https://www.cnblogs.com/-roc/p/17021338.html

相关文章