锚点跳转-附带CSS样式 & 阻止页面刷新技术方案

问题:触发浏览器默认锚点行为,首次点击,刷新页面,虽然回到顶部,但未保存数据被清空。

js 复制代码
<!-- 原始 -->

<span id="topAnchor"></span>

<!-- 回到顶部按钮 -->

<a href="#topAnchor" class="back-top-btn">

<a-icon type="arrow-up" />

</a>

解决方案:阻止默认行为 + 编程控制

js 复制代码
<a @click.prevent="scrollToTop">回到顶部</a>


scrollToTop() {

    const anchor = document.getElementById('topAnchor')

        if (anchor) {

        anchor.scrollIntoView({ behavior: 'smooth', block: 'start' })

        } else {

        window.scrollTo({ top: 0, behavior: 'smooth' })

    }

}

关键技术点

  • @click.prevent - 阻止默认链接行为
  • scrollIntoView() - 编程式控制滚动
  • behavior: 'smooth' - 添加平滑动画
  • URL保持不变 - 避免路由重载

适用场景

  • 单页应用(SPA)
  • 需要平滑滚动效果
  • 希望保持URL稳定的场景
js 复制代码
配合CSS:

<a @click.prevent="scrollToTop">回到顶部</a>


scrollToTop() {

    const anchor = document.getElementById('topAnchor')

        if (anchor) {

        anchor.scrollIntoView({ behavior: 'smooth', block: 'start' })

        } else {

        window.scrollTo({ top: 0, behavior: 'smooth' })

    }

}


// css:回到顶部按钮样式
.back-top-btn {
    position: fixed;
    right: 80px;
    bottom: 100px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: #1890ff;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transition: all 0.3s;
    cursor: pointer;
    z-index: 1000;
    &:hover {
    background-color: #40a9ff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    transform: translateY(-2px);
}

 
 &:active {
    transform: translateY(0);
 }
}

效果图

相关推荐
To_OC8 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
咩咩啃树皮9 小时前
第40篇:Vue3组件化开发精讲——组件拆分、复用、父子通信、工程化架构
java·前端·架构
阳光是sunny9 小时前
LangGraph中的Reducer是什么
前端·人工智能·后端
触底反弹9 小时前
一文搞懂 Tailwind CSS 弹性布局:从原理到实战
前端·css·html
阳光是sunny9 小时前
从链到图:LangGraph 入门基础全解析
前端·人工智能·后端
To_OC9 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
小林ixn10 小时前
从 ??= 到 onKeyDown:一个 React 组件的“自我修养”
前端·javascript·react.js
REDcker10 小时前
显示分辨率标准对照详解
前端·网络·分辨率·显示·屏幕
এ慕ོ冬℘゜10 小时前
前端实战:jQuery 多条件联合搜索(标题模糊查询 + 日历时间段筛选)
前端·javascript·jquery
武子康11 小时前
Search Console Platform Properties 扩大 SEO 资产边界:从 Page Ranking 到 Topic Coverage(5 类误读边界 + 3 表数据层设计)
前端·人工智能·后端