美文网首页
土炮方式做到滚动内容自动高亮菜单

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

作者: 山哥Samuel | 来源:发表于2022-11-16 09:26 被阅读0次

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

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

        <Layout style={{marginLeft: '-1.5em'}}>
            <Layout.Sider style={{background: 'rgb(37, 48, 56)'}}>
                <Affix offsetTop={165}>
                    <Menu style={{background: 'rgb(37, 48, 56)'}} theme='dark' mode='inline' selectedKeys={[selectedMenuItem]} items={items} onSelect={selectMenuItem} />
                </Affix>
            </Layout.Sider>
            <Layout.Content>
               ...
            </Layout.Content>
        </Layout>

给内容定义锚点 <a className="anchor" id='${anchor-name}'></a>

            <Layout.Content>
                <div className="opPageContent">
                    {/* <h2 className='colorRed'>{formatMsg("WLC")}</h2><br/> */}
                    <a className="anchor" id='ICE Scores'></a>
                    <h2>Current ICE scores by services</h2>
                    <div style={style}>
                        <IceChartForAll
                            data={props.iceScoreList}
                            metaData = {props.metaData}
                            onSvsChanged = {onSvsChanged}
                            gotoService={viewIceScoreHistory}/>
                    </div>
                    <a className="anchor" id='Jenkins Activities'></a>
                    <h2>Current Jenkins activity by microservices</h2>
                    <div style={style}>
                        <JenkinsActivityChartForAll
                            data={props.jenkinsActivityList}
                            metaData = {props.metaData}
                            onSvsChanged = {onSvsChanged}
                            gotoMicroService={viewMSIceScoreHistory}/>
                    </div>
                    {/* <h1>ICE Score History by services</h1>
                    <div style={style}>
                    <LinePlotWithSlider/>
                    </div> */}
                    <a className="anchor" id='Incompliant Pipelines'></a>
                    <h2>Incompliant pipeline</h2>
                    <div>
                        <span>No data means all good!</span>
                        <IncompliantList />
                    </div>
                </div>
            </Layout.Content>

锚点的样式:

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: <BarChartOutlined /> }, // remember to pass the key prop
        { label: 'Jenkins Activities', key: '2', icon: <LineChartOutlined /> }, // which is required
        { label: 'Incompliant Pipelines', key: '3', icon: <WarningOutlined /> },
    ];

    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 (
        <Layout style={{marginLeft: '-1.5em'}}>
            <Layout.Sider style={{background: 'rgb(37, 48, 56)'}}>
                <Affix offsetTop={165}>
                    <Menu style={{background: 'rgb(37, 48, 56)'}} theme='dark' mode='inline' selectedKeys={[selectedMenuItem]} items={items} onSelect={selectMenuItem} />
                </Affix>
            </Layout.Sider>
            <Layout.Content>
                <div className="opPageContent">
                    {/* <h2 className='colorRed'>{formatMsg("WLC")}</h2><br/> */}
                    <a className="anchor" id='ICE Scores'></a>
                    <h2>Current ICE scores by services</h2>
                    <div style={style}>
                        <IceChartForAll
                            data={props.iceScoreList}
                            metaData = {props.metaData}
                            onSvsChanged = {onSvsChanged}
                            gotoService={viewIceScoreHistory}/>
                    </div>
                    <a className="anchor" id='Jenkins Activities'></a>
                    <h2>Current Jenkins activity by microservices</h2>
                    <div style={style}>
                        <JenkinsActivityChartForAll
                            data={props.jenkinsActivityList}
                            metaData = {props.metaData}
                            onSvsChanged = {onSvsChanged}
                            gotoMicroService={viewMSIceScoreHistory}/>
                    </div>
                    {/* <h1>ICE Score History by services</h1>
                    <div style={style}>
                    <LinePlotWithSlider/>
                    </div> */}
                    <a className="anchor" id='Incompliant Pipelines'></a>
                    <h2>Incompliant pipeline</h2>
                    <div>
                        <span>No data means all good!</span>
                        <IncompliantList />
                    </div>
                </div>
            </Layout.Content>
        </Layout>
    )
}
    

export default withRouter(Home)

相关文章

网友评论

      本文标题:土炮方式做到滚动内容自动高亮菜单

      本文链接:https://www.haomeiwen.com/subject/gppsxdtx.html