VueJS:如何在滚动位置后动态更改CSS类 [英] VueJS: How to dynamically change a CSS class after a scroll position

查看:465
本文介绍了VueJS:如何在滚动位置后动态更改CSS类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用vueJs和 bootstrap 创建了一个webapp。我想在某个元素的更改CSS类之后



我想要的东西如下:

 < div:class ={classA:scrollPosition< 100,classB:scrollPosition> 100}> 
< / div>

我发现的一个选择是使用 vue-scroll ,这似乎很有前途,但不工作



是否还有其他本地方式可以使用同样的方式?

$

  const app = new Vue({

el:'#app',

data:{
scrollPosition:null
},

方法:{
updateScroll(){
this.scrollPosition = window.scrollY
}
},

installed(){
window.addEventListener('scroll',this.updateScroll);
}

})

您也可以在destroy上删除eventListener,如下所示:

  destroy(){
window.removeEventListener('scroll',this.updateScroll)
}


I am creating a webapp with vueJs and bootstrap. I want to change CSS class of an element after a particular amount of scroll, Is there some vue way of doing it.

I want something like following:

<div :class="{classA: scrollPosition < 100, classB: scrollPosition > 100}">
</div>

One option I found is by using vue-scroll, which seems promising, but not working.

Is there some other native way as well to achive the same?

解决方案

You could try to make it like this

const app = new Vue({

  el: '#app',

  data: {
    scrollPosition: null
  },

  methods: {
    updateScroll() {
      this.scrollPosition = window.scrollY
    }
  },

  mounted() {
    window.addEventListener('scroll', this.updateScroll);
  }

})

You could also remove eventListener on destroy, something like this:

destroy() {
  window.removeEventListener('scroll', this.updateScroll)
}

这篇关于VueJS:如何在滚动位置后动态更改CSS类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆