【问题标题】:Configure IntersectionObserver to change value of *.isIntersecting based on X pixels配置 IntersectionObserver 以根据 X 像素更改 *.isIntersecting 的值
【发布时间】:2017-11-16 12:07:18
【问题描述】:

我有交点观察者对象,它可以工作,但我希望它在某个元素超过或位于交点底部 100 像素时通知我。

使用默认配置,一旦元素完全在视图中,它只会更改 .isIntersection 的值。但是当元素在视口上方或下方 100 像素时,我想做一些事情。

这是我的代码:

var iObserver = new IntersectionObserver(function(element) {
  console.log('elementi', element); // I want to trigger here when elementi is 100px or less of distance to the viewport.
});

var el;
for (var i = 0; i < elements.length; i++) {
  el = elements[i];
  console.log('eli', el);
  iObserver.observe(el);
}

更新

感谢用户的回答我使用了这个并且它有效:

var iObserver = new IntersectionObserver(function(entryEvent) {
 //...
}, {'rootMargin': '100px 0px 100px 0px'});

【问题讨论】:

    标签: javascript ecmascript-6 polyfills intersection-observer


    【解决方案1】:

    您可以在传递给观察者的选项中定义rootMargin 顶部和底部。

    在演示中,悬停红色矩形,当它与.container 的距离达到10px 时,调用观察者:

    const options = {
      root: document.querySelector('.container'),
      rootMargin: '10px 0px 10px 0px',
    };
    
    let i = 0;
    
    const iObserver = new IntersectionObserver((entries) => console.log(`intersection ${i++}`), options);
    
    iObserver.observe(document.querySelector('.element'));
    .container {
      position: relative;
      height: 20px;
      background: lightblue;
    }
    
    .element {
      position: absolute;
      top: calc(100% + 30px);
      height: 100px;
      width: 100px;
      background: red;
      margin-bottom: 20px;
      transition: top 5s;
    }
    
    .element:hover {
      top: calc(100% - 30px);
    }
    
    .as-console-wrapper {
      height: 50px;
    }
    <div class="container">
      <div class="element">1</div>
    </div>

    【讨论】:

    • 它工作了我刚刚作为配置选项传递:{ 'rootMargin': '100px 0px 100px 0px'}
    • 我使用了 10px,因为我在 sn-p 中没有足够的空间 :)
    • 欢迎兄弟/姐妹 :)
    猜你喜欢
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2011-10-15
    • 2017-11-27
    相关资源
    最近更新 更多