【问题标题】:How to expand the video container smoothly as it comes to viewport in Nuxtjs在 Nuxtjs 的视口中如何平滑地扩展视频容器
【发布时间】:2021-10-02 16:47:14
【问题描述】:

我必须制作一个与one 非常相似的网页。我为此使用 Nuxt,我在以完全相同的方式使视频扩大和缩小时遇到了问题。

我已尝试在StackBlitz here 上复制该问题。该指令实际上无法正常工作。我想在视频进入视口后立即实现完全相同的过渡。

自定义指令的代码 -

export default {
  directives: {
    inView: {
      isLiteral: true,
      inserted: (el, binding, _) => {
        const isInView = () => {
          const rect = el.getBoundingClientRect();
          const inView = (rect.width > 0 && rect.height > 0 && rect.top >= 0 &&
            (rect.bottom + 100) <= (window.innerHeight || document.documentElement.clientHeight));
          if (inView) {
            el.classList.add(binding.value);
            // window.removeEventListener('scroll', isInView);
          } else {
            el.classList.remove(binding.value);
          }
        };
        window.addEventListener('scroll', isInView);
        isInView();
      }
    }
  }
}

【问题讨论】:

    标签: javascript vue.js nuxt.js vue-directives


    【解决方案1】:

    使用IntersectionObserver 代替scroll 侦听器来跟踪元素何时进入或离开视图。以下观察者创建了一个阈值为 30% 的 IntersectionObserver,在视图中将 binding.arg 值作为 CSS 类添加到元素:

    export default {
      directives: {
        inView: {
          mounted(el, binding) {
            const threshold = 0.3 // trigger callback when element is 30% in view
            const observer = new IntersectionObserver(entries => {
              const elem = entries[0]
              if (elem.intersectionRatio >= threshold) {
                el.classList.add(binding.arg);
              } else {
                el.classList.remove(binding.arg);
              }
            }, { threshold })
            observer.observe(el)
            binding.instance.observer = observer
          },
          unmounted(el, binding) {
            binding.instance.observer.disconnect()
          },
        }
      },
    }
    

    然后使用video-wrapper 元素上的指令进行动画处理(其中scale 是动画类):

    <div v-in-view:scale class="video-wrapper">
    

    demo

    【讨论】:

    • 我已经复制并粘贴了您的代码,但它不起作用。虽然它正在 StackBlitz 上工作。实际上,即使是我在mounted()unmounted() 中添加的日志也没有触发
    • 是不是因为我用的是 Nuxt js?
    猜你喜欢
    • 1970-01-01
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 2016-02-21
    • 2019-04-05
    • 1970-01-01
    相关资源
    最近更新 更多