Vue.js检查滚动条是否滚动到元素

时间:2017-08-20 19:15:17

标签: vue.js

我的html代码中有一个元素

addCart

现在我希望<div class="my_div"> </div> 当用户滚动到此元素时。如果alert位于页面的中心,我如何使用Vue执行此操作?

1 个答案:

答案 0 :(得分:0)

您应该使用vue $ ref。

HTML

<div id="PAGE-MAIN-PARENT-DIV" v-scroll="handleScroll">
  <div ref="my_div" > </div>
</div>

JS

Vue.directive('scroll', {
  inserted: function (el, binding) {
    let f = function (evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f)
      }
    }
    window.addEventListener('scroll', f)
  }
})

内部Vue方法:

methods: {
    handleScroll (evt, el) {
      if (!this.$refs.my_div) {
        return false
      }

      const emissionYOfsset = this.$refs.my_div.$el.offsetTop

      // Change this condition in order to fit your requirements
      if (window.scrollY + window.innerHeight >= emissionYOfsset &&
        window.scrollY <= emissionYOfsset) {
        console.log('currently in screen')

        // Do you want to continue with the event?
        return false
      }
    }
  }
相关问题