html页面刷新回到顶部_回到页面指定位置的三种方式

107623aaf29ebba5d5b91533e56a8689.png

a 标签

首先放出html

我是顶部

第一种方式回到顶部

第二种方式回到顶部

第三种方式回到顶部

然后具体操作步骤如下

  1. 将a标签放到指定元素的附近
  2. 然后通过点击事件生成 a 标签
  3. 触发a标签事件
  4. 删除a标签

const backTop1 = document.getElementById("backTop1")

backTop1.addEventListener("click", function (e) {

let a = document.createElement("a")

a.href = "#topAnchor"

e.target.appendChild(a)

a.onclick = function (e) {

e.stopPropagation()

}

a.click()

e.target.removeChild(a)

})

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue项目页面刷新后,页面回到顶部的原因是浏览器刷新时会重新加载页面,所有的状态都会被重置。因此,浏览器会将页面滚动位置重置为顶部。 要解决这个问题,可以使用浏览器的本地存储(Local Storage)或者Session Storage来保存页面的滚动位置。在页面加载时,可以从本地存储中读取滚动位置并将页面滚动到该位置。这样可以避免页面刷新后滚动位置被重置的问题。 例如,在Vue中可以使用`window.localStorage`来保存和读取滚动位置: ```javascript // 保存滚动位置 window.localStorage.setItem('scrollPosition', window.pageYOffset); // 读取滚动位置并滚动到该位置 const scrollPosition = window.localStorage.getItem('scrollPosition'); if (scrollPosition) { window.scrollTo(0, parseInt(scrollPosition)); } ``` 在Vue中也可以使用Vue Router的`scrollBehavior`选项来控制页面切换时的滚动行为,并在页面刷新时恢复滚动位置: ```javascript const router = new VueRouter({ mode: 'history', routes: [...], scrollBehavior(to, from, savedPosition) { if (savedPosition) { return savedPosition; } else { return { x: 0, y: 0 }; } } }); // 在页面刷新时恢复滚动位置 router.beforeEach((to, from, next) => { const scrollPosition = window.localStorage.getItem('scrollPosition'); if (scrollPosition) { window.scrollTo(0, parseInt(scrollPosition)); window.localStorage.removeItem('scrollPosition'); } next(); }); router.afterEach((to, from) => { // 保存滚动位置 window.localStorage.setItem('scrollPosition', window.pageYOffset); }); ``` 这样,在页面刷新时会从本地存储中读取滚动位置并将页面滚动到该位置。在页面切换时也会保存滚动位置,以便在页面返回时可以恢复滚动位置

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值