Vue.js 2可以获得正文滚动位置但不能设置正文滚动位置

时间:2017-09-17 06:51:41

标签: javascript vue.js

我有一个Vue.js应用程序,我打开一个模态,需要将它下面的主体设置到一个固定的位置,以防止它在移动设备上滚动。这当然会将其滚动到顶部。在打开模态之前,我得到滚动位置并将其设置为:

this.bposition = document.body.scrollTop
console.log(document.body.scrollTop)

这很好用,我可以在控制台中输出正确的位置。但是,当我关闭我的模态时,我会尝试这样做:

  console.log(this.bposition) // proves my close function is running and gets the correct value
  var el = document.querySelector('body')
  el.scrollLeft = 0 // have tried with and without this line
  el.scrollTop = this.bposition

但无济于事,页面不会滚动。我也试过了页面中的各种元素,它们都没有滚动。

1 个答案:

答案 0 :(得分:0)

UGH。我找到了解决方案。显然,即使正在修复我的身体的课程在模态关闭时被删除,但它的移除速度还不够快。我通过引入超时来解决这个问题:

setTimeout(() => {
        el.scrollTop = this.bposition
      }, 500)

更新: 有点快,我发现函数(在外部代码中)删除了类并在我的调用之前将其复制,这样做效果更好:

  var el = document.querySelector('body')
  el.classList.remove('with-modal')
  el.scrollTop = this.bposition