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

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

问题描述

我正在使用 vueJs 和 bootstrap 创建一个 web 应用程序.我想在滚动特定量后更改元素的 CSS 类, 有没有什么vue的方法.

我想要如下内容:

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

是否有其他本地方式也可以达到同样的目的?

解决方案

你可以尝试这样做

const app = new Vue({el: '#app',数据: {滚动位置:空},方法: {更新滚动(){this.scrollPosition = window.scrollY}},安装(){window.addEventListener('scroll', this.updateScroll);}})

你还应该考虑在组件被销毁时移除事件监听器,以防止泄漏:

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 should also consider removing event listener when component is being destroyed, in order to prevent leaks:

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

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

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