twitter-bootstrap VueJS:如何在滚动位置后动态更改 CSS 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41095814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 00:26:08  来源:igfitidea点击:

VueJS: How to dynamically change a CSS class after a scroll position

htmlcsstwitter-bootstrapvue.js

提问by Saurabh

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

我正在使用 vueJs 和bootstrap创建一个 webapp 。我想在滚动特定量后更改元素的CSS 类,是否有一些 vue 方法可以做到这一点。

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.

我发现的一种选择是使用vue-scroll,这看起来很有希望,但不起作用

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

还有其他一些本地方式也可以实现相同的目标吗?

回答by Belmin Bedak

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:

您还可以在销毁时删除 eventListener,如下所示:

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