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

效果图

相关推荐
COOLMO研究AI3 分钟前
Next.js App Router 中 sitemap、robots 与 canonical 的配置与排查
前端·web·js·网站优化
DyLatte27 分钟前
AI 给了我 8 个优化方案,全都是对的,但没有一个有用
前端·后端·程序员
AI情绪识别开源30 分钟前
检信ALLEMOTION 认知评估分析器 · WebSocket 推送数据文档
javascript
OpsEye36 分钟前
公司内部全员使用 AI,如何保证会话合规、行为可审计?
javascript·ai编程
the局外人36 分钟前
一座不够大的城市,装下了我毕业后的成长
前端·程序员·求职
涛涛ing1 小时前
周下载量1.1亿的Tailwind,为什么养不活自己?
前端
变与不变8061 小时前
JS事件机制精讲
前端·javascript
装备研究社1 小时前
Promise 的五个状态,90% 的人只说对了三个
前端
小聪7081 小时前
elpis-core 抽离 npm 包过程的难点和卡点
前端·架构
钱栈up2 小时前
坯料管理导入功能bug修复:只改前端一个文件就解决问题
前端·bug