如何在 Vue 中滚动时更改 css [英] How to change css while scrolling in Vue

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

问题描述

我决定在一个项目中学习 Vue.js,但我不知道如何在类似的距离后跟踪窗口滚动和动态更改 CSS,就像我使用 JQuery 所做的那样:

$(window).scroll(function() {if($(window).scrollTop() >= 100) {$('header').addClass('fixed');} 别的 {$('header').removeClass('fixed');}});

解决方案

您可以使用 自定义指令 并将其绑定到 Vue 实例中的任何组件或元素.

假设你有一个

并命名你的指令 on-scroll 你会更新你的 div:<div on-scroll="handleScroll"> 其中 handleScroll 是你的 Vue 实例中用来处理滚动事件的方法.

指令:

Vue.directive('on-scroll', {插入:函数(el,绑定){让 f = 函数 (evt) {如果(绑定.值(evt,el)){window.removeEventListener('scroll', f)}}window.addEventListener('scroll', f)}})

Vue 实例:

new Vue({el: '#el',方法: {handleScroll: (event, el) =>{如果(window.scrollY >= 300){el.classList.add('固定');} 别的 {el.classList.remove('固定');}}}});

i decided to learn Vue.js on a project and i can't get how i can track window scroll and dynamicly change CSS after some distance similar, like i did it with JQuery:

$(window).scroll(function() {
      if($(window).scrollTop() >= 100) {
        $('header').addClass('fixed');
      } else {
        $('header').removeClass('fixed');
      }
    });

解决方案

You can use a Custom Directive and bind it to any component or element in your Vue instance.

So say you have a <div> and name your directive on-scroll you would update your div: <div on-scroll="handleScroll"> where handleScroll is the method in your Vue instance that is going to, well, handle the scroll event.

Directive:

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

Vue Instance:

new Vue({
  el: '#el',
  methods: {
    handleScroll: (event, el) => {
       if ( window.scrollY >= 300 ) {
          el.classList.add('fixed');
       } else {
          el.classList.remove('fixed');
       }
    }
  }
});

这篇关于如何在 Vue 中滚动时更改 css的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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