土炮方式做到滚动内容自动高亮菜单

在我们看那种一长页的技术文档的时候(右边固定是菜单目录),当你滚动到某一个新的章节,右边的菜单也会滚到跟你现在章节相应的地方,并高亮该链接表示“已选定”。
我用过AntD和一些组件库,并没发现有这个功能,于是自己实现一个。

我们用了AntD的菜单和Affix来固定菜单:

        
            
                
                    
                
            
            
               ...
            
        

给内容定义锚点

            
                
{/*

{formatMsg("WLC")}


*/}

Current ICE scores by services

Current Jenkins activity by microservices

{/*

ICE Score History by services

*/}

Incompliant pipeline

No data means all good!

锚点的样式:

a.anchor {
    display: block;
    position: relative;
    top: -180px;
    visibility: hidden;
}

现在我们来监控一下滚动位置:

    useEffect(()=> {
        window.addEventListener("scroll", setScroll);
        return () => {
            window.removeEventListener("scroll", setScroll);
        };
    }, [])

        // Will try to highlight the menu when it is scrolled to the anchor.
    const setScroll = (event) => {
        let minKey = 1
        for(let i=items.length-1; i>=0; i--) {
            let e = items[i]
            let id = e.label
            let rect = document.getElementById(id).getBoundingClientRect()

            if (rect.top < 200) {
                minKey = e.key
                break
            }
        }

        setSelectedMenuItem(`${minKey}`)
    }

好的,大功告成!
附上完整示例:

import React, {useState, useEffect} from 'react';
import { withRouter } from 'react-router-dom';
import IceChartForAll from './iceChartForAll'
import JenkinsActivityChartForAll from './jenkinsActivityChartForAll'
import IncompliantList from './incompliantList'
import {Layout, Menu, Affix} from "antd";
import './dashboard.css'
import { BarChartOutlined, LineChartOutlined, WarningOutlined } from "@ant-design/icons";

const Home = (props) => {
    const [selectedMenuItem, setSelectedMenuItem] = useState('1')

    // Do it once
    useEffect(()=> {
        if(props.iceScoreList.length == 0){
            props.getIceScoresByService({})
        }
        if(props.jenkinsActivityList.length == 0){
            props.getJenkinsActivityByMicro()
        }

        window.addEventListener("scroll", setScroll);
        return () => {
            window.removeEventListener("scroll", setScroll);
        };
    }, [])

    const gotoService = (id) => {
        let pathname = `/service/detail/${id}`
        props.history.push({
            pathname
        })
    }

    const gotoMicroService = (id) => {
        let pathname = `/microservice/detail/${id}`
        props.history.push({
            pathname
        })
    }

    const viewIceScoreHistory = (id) =>{
        props.history.push({
            pathname: `/service/icehistory/${id}`,
        })
    }

    const viewMSIceScoreHistory = (id) =>{
        props.history.push({
            pathname: `/microservice/icehistory/${id}`,
        })
    }

    const onSvsChanged = (value, props, setData) => {
        if (value) {
            setData(props.data?.filter(e => e.svs == value))
        } else {
            setData(props.data)
        }
    }

    // Will try to highlight the menu when it is scrolled to the anchor.
    const setScroll = (event) => {
        let minKey = 1
        for(let i=items.length-1; i>=0; i--) {
            let e = items[i]
            let id = e.label
            let rect = document.getElementById(id).getBoundingClientRect()

            if (rect.top < 200) {
                minKey = e.key
                break
            }
        }

        setSelectedMenuItem(`${minKey}`)
    }


    const style = {
        margin: '30px 0'
    }

    const items = [
        { label: 'ICE Scores', key: '1', icon:  }, // remember to pass the key prop
        { label: 'Jenkins Activities', key: '2', icon:  }, // which is required
        { label: 'Incompliant Pipelines', key: '3', icon:  },
    ];

    const selectMenuItem = (item) => {
        setSelectedMenuItem(item.key)
        let es = items.filter(e => e.key == item.key)
        if (es.length > 0) {
            let e = es[0]
            location.hash = "#" + e.label;
        }
    }

    return (
        
            
                
                    
                
            
            
                
{/*

{formatMsg("WLC")}


*/}

Current ICE scores by services

Current Jenkins activity by microservices

{/*

ICE Score History by services

*/}

Incompliant pipeline

No data means all good!
) } export default withRouter(Home)

你可能感兴趣的:(土炮方式做到滚动内容自动高亮菜单)