vue记录滚动位置

BestLuckBoy 2017-08-08 11:10:16
1.问:有一个图片列表页(类似某宝),点击任何一个进去之后再返回,返回到刚刚访问的位置,一个很常见的需求。
2.尝试过原生js,利用scrollTop和localStorage结合,点击的时候记录scrollTop值;也试过vue-route的scrollBehavior,都没奏效
3.我用的是vue单页面应用
js方法代码如下:
var map = {};
window.onhashchange = function() {
document.body.scrollTop = 0;
}
window.onscroll = function() {
if (document.body.scrollTop) {
// 存
map[location.hash] = document.body.scrollTop;
} else {
var timer = null;
timer = setInterval(function(){
if (document.body.scrollTop == map[location.hash]) {
clearInterval(timer);
} else {
document.body.scrollTop = map[location.hash];
}
}, 20);
}
}

vue scrollBehavior方法代码如下:
if (savedPosition) {
// savedPosition is only available for popstate navigations.
return savedPosition
} else {
const position = {}
// new navigation.
// scroll to anchor by returning the selector
if (to.hash) {
position.selector = to.hash

// specify offset of the element
if (to.hash === '#eg') {
position.offset = { y: 100 }
}
}
// check if any matched route config has meta that requires scrolling to top
if (to.matched.some(m => m.meta.scrollToTop)) {
// cords will be used if no selector is provided,
// or if the selector didn't match any element.
position.x = 0
position.y = 500
}
// if the returned position is falsy or an empty object,
// will retain current scroll position.
return position
}
...全文
910 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaotuni 2017-08-11
  • 打赏
  • 举报
回复
大概思路是:
路由里 onLeave的时候,记录当前的 scrollTop,回来的时候
onEnter的时候,将 window.body.scrollTop = 之前的保存的值就可以了。
当作看不见 2017-08-08
  • 打赏
  • 举报
回复
记录位置,没必要这么麻烦,多加几个锚点,每个图片来一发,

39,087

社区成员

发帖
与我相关
我的任务
社区描述
HTML5是构建Web内容的一种语言描述方式。HTML5是互联网的下一代标准,是构建以及呈现互联网内容的一种语言方式.被认为是互联网的核心技术之一。
社区管理员
  • HTML5社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧