锚点跳转-附带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);
 }
}

效果图

相关推荐
@大迁世界10 小时前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊12 小时前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome88813 小时前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌13 小时前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易13 小时前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常14 小时前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师14 小时前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么14 小时前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒14 小时前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端
hunter_07614 小时前
一次 iOS 真机签名 409 的完整排查:证书、设备、描述文件为什么总是"对不上"
前端