【问题标题】:IntersectionObserver and transform transitionIntersectionObserver 和转换转换
【发布时间】:2021-01-11 03:24:13
【问题描述】:

我在 Stackoverflow 上的第一篇文章

我正在尝试用intersectionObserver 构建一个简单的滚动效果。这个想法是当一个项目离开视口时,它被缩放到 0,并且在完全可见时缩放到 1。我真的不知道这是否是构建这种效果的好方法......但似乎可以正常工作,除了:

滚动时元素上的“跳跃”效果存在一些问题。我想 requestAnimationsFrame 应该可以解决它,但我无法实现它,我需要一些帮助来理解它是如何工作的。

一支笔可见here

注意:初学JS,

谢谢。

const sectionScaleOption = {
     root: null,
     rootMargin: '0px',
     threshold: [
         0.0,
         0.05,
         0.1,
         0.15,
         0.2,
         0.25,
         0.3,
         0.35,
         0.4,
         0.45,
         0.5,
         0.55,
         0.6,
         0.65,
         0.7,
         0.75,
         0.8,
         0.85,
         0.9,
         0.95,
         1.0,
     ],
 };

observer = new IntersectionObserver(entries => {
entries.forEach(entry => {  
  const ratio = entry.intersectionRatio;
  const section = entry.target;
  if (ratio > 0) {
  section.classList.add('forTest');
  console.log(ratio);
  section.style.transform = `scale(${ratio})`;
  } else {
  section.classList.remove('forTest');
  console.log('out');
 }
});
}, sectionScaleOption);

const sectionToScale = document.querySelector('.section');


observer.observe(sectionToScale);

【问题讨论】:

    标签: javascript css-transforms requestanimationframe intersection-observer


    【解决方案1】:

    为了更好的结果,最后使用了: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

    function buildThresholdList() {
      let thresholds = [];
      let numSteps = 100;
    
      for (let i=1.0; i<=numSteps; i++) {
        let ratio = i/numSteps;
        thresholds.push(ratio);
      }
    
      thresholds.push(0);
      return thresholds;
    }
    
    
    const obsOptnScrollOpct = {
      root: null, 
      rootMargin: '0px',
      threshold: buildThresholdList()
    };
    

    这并不完美,如果有任何其他建议/建议,我将非常高兴。

    【讨论】:

      猜你喜欢
      • 2016-05-14
      • 2021-01-24
      • 2017-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      • 1970-01-01
      • 2012-11-19
      • 2012-05-07
      相关资源
      最近更新 更多