vue在hash路由模式下实现点击定位滑动

背景:一般是使用锚点来实现dom的定位,但在hash模式下,这种方式不行,会刷新路由,没法实现dom定位的效果。

其实scrollIntoView就可以解决这个问题,scrollIntoView可以将调用它的元素滚动到浏览器窗口的可见区域。

代码实现:

css 复制代码
<!--html模块-->
<div class="bottom-wrapper">
        <div class="left">
            <div @click="goToDom(item.value)" v-for="(item,index) in menuList" :key="index" class="menu-item">
                <span>{{item.name}}</span>
            </div>
        </div>
        <div class="right">
            <div class="scroll-container">
                <div class="scroll-page" ref="modelA">
                    <div class="head">模块1</div>
                 </div>
                <div class="scroll-page" ref="modelB">
                    <div class="head">模块2</div>
                 </div>
                <div class="scroll-page" ref="modelC">
                    <div class="head">模块3</div>
                 </div>
            </div>
</div>
css 复制代码
//关键方法
//跳转到指点的位置
 const goToDom = (refName) => {
        proxy.$refs[refName].scrollIntoView({block: 'start', behavior: 'smooth'});
  }
css 复制代码
    .bottom-wrapper {
        display: flex;
        margin: 10px;
        scroll-behavior: smooth;
        height: calc(100% - 365px);

        .left {
            width: 150px;
            @include box-ht;
            display: flex;
            flex-direction: column;
            align-items: center;

            .menu-item {
                margin: 5px 0;
                border-bottom: 1px solid $theme-bg;
                padding-bottom: 5px;
                color: #000000;
                &:hover{
                    cursor: pointer;
                }
            }
        }

        .right {
            margin-left: 10px;
            width: calc(100% - 150px);
            height: 100%;

            .scroll-container {
                /* 核心代码:缓慢滚动过渡 */
                scroll-behavior: smooth;
                display: block;
                height: 100%;
                overflow-y: scroll;
            }

            .scroll-page {
                position: relative;
                @include box-ht;
                margin: 10px 0;

                .head {
                    font-weight: bold;
                    border-bottom: 1px solid $theme-bg;
                    padding-bottom: 5px;
                }
            }
        }
    }
相关推荐
二川bro4 分钟前
第33节:程序化生成与无限地形算法
前端·算法·3d·threejs
QDKuz11 分钟前
掌握Vue2转Vue3, Options API 转 Composition API
前端·javascript·vue.js
老前端的功夫17 分钟前
前端Echarts性能优化:从卡顿到流畅的百万级数据可视化
前端·javascript
进击的野人19 分钟前
深入解析localStorage:前端数据持久化的核心技术
前端·javascript
懵圈23 分钟前
第2章:项目启动 - 使用Vite脚手架初始化项目与工程化配置
前端
Mh24 分钟前
如何优雅的消除“if...else...”
前端·javascript
火鸟235 分钟前
给予虚拟成像台尝鲜版十之二,完善支持 HTML 原型模式
前端·html·原型模式·通用代码生成器·给予虚拟成像台·快速原型·rust语言
逍遥江湖1 小时前
Vue3 + TypeScript 项目框架搭建指南
前端
lapiii3581 小时前
[前端-React] Hook
前端·javascript·react.js
QuantumLeap丶1 小时前
《uni-app跨平台开发完全指南》- 07 - 数据绑定与事件处理
vue.js·ios·uni-app