实现头部Sticky 粘性布局,并且点击菜单滑动到相应位置

摘要:该代码实现了一个带粘性导航栏的页面滚动功能。通过el-button组件绑定点击事件,调用scrollToCity方法实现平滑滚动到对应ID的区块。使用scrollIntoView的smooth参数实现平滑滚动效果,并通过CSS的position:sticky使导航栏固定在顶部。注意事项包括:祖先元素不能设置overflow:hidden,否则会导致粘性布局失效。导航栏设置了z-index确保始终显示在前端。

复制代码
<template>
<div>
    <div class="buildNameClass">
         <!--给导航项绑定点击事件-->
         <el-button type="primary" @click="scrollToCity('one')">工商信息</el-button>
         <el-button type="primary" @click="scrollToCity('two')">股权关系</el-button>
         <el-button type="primary" @click="scrollToCity('three')">城市布局</el-button>
         <el-button type="primary" @click="scrollToCity('four')">分支机构</el-button>
    </div>
    <div>
        <!--给目标元素加 id -->
        <div class="thirdClass" id="city-one"></div>
        <div class="eighthClass" id="city-two"></div>
        <div class="eighthClass" id="city-three"></div>
        <div class="fourthClass" id="city-four"></div>
    </div>
</div>
<template>

<script>
export default {
    methods: {
        //使用 scrollIntoView({behavior: 'smooth'}) 实现平滑滚动
        scrollToCity(cityId) {
            const element = document.getElementById(`city-${cityId}`);
            if (element) {
                element.scrollIntoView({
                    behavior: 'smooth', // 平滑滚动
                    block: 'start'       // 对齐顶部
                });
            }
        },
    }
}
</script>

<style>
    //css样式粘性布局
    //要注意相关祖先组件不能有overflow: hidden;会导致粘性布局失效
    //如果滚动是body层级控制,则要确保从 .buildNameClass 到 <body> 之间没有任何 overflow:                     hidden;
    .buildNameClass{
        width: 100%;
        height: 50px;
        margin-top: 20px;
        border-radius: 6px;
        background-color: rgba(255,255,255,0.74);
        font-size: 19px;
        font-weight: bold;
        display: flex;
        flex-direction: row;
        align-items: center;
        position: sticky;
        position: -webkit-sticky;
        top: 50px;
        z-index: 9999;
    }
</style>
相关推荐
回眸&啤酒鸭5 分钟前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户693717500138414 分钟前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员17 分钟前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子32 分钟前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒38 分钟前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend2 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
小宋10212 小时前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互
大包子2 小时前
structuredClone vs lodash.cloneDeep:核心差异与选型指南
javascript·vue.js
海码事务所2 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端
田威AI2 小时前
图片内文字翻译的规格:输入输出、保真、自动化、时间与费用
前端·计算机视觉