简体   繁体   English

Intersection Observer API 不使用隐藏元素

[英]Intersection Observer API not working with hidden elements

I am trying to observe a hidden element.我试图观察一个隐藏的元素。 I have an element which has style set to display: none .我有一个元素的样式设置为display: none I want when my element intersect it will perform my action ie: Play the video.我希望当我的元素相交时它会执行我的操作,即:播放视频。 I am sharing my sample code below我在下面分享我的示例代码

 var options = {threshold: 0.5 }     

 var circle = document.getElementById('content_video');

 var observer = new IntersectionObserver(entries => {
     var [{ isIntersecting }] = entries
     if (isIntersecting) {
         player.play();
         player.ima.getAdsManager().resume();
     } else {
         player.ima.getAdsManager().pause();
     }
 }, options);

 window.addEventListener('load', () => {
     if ('IntersectionObserver' in window) observer.observe(circle);
 }, false);

This is normal behaviour, because element with display:none cannot be reached and ignoring by browser这是正常行为,因为无法访问带有display:none的元素并被浏览器忽略

Try set other styles instead display:none .尝试设置其他 styles 代替display:none Example, use opacity or width and height 0 with overflow: hidden例如,使用不透明度或宽度和高度 0 与溢出:隐藏

Unfortunately if your goal is to use the intersection observer to lazy load the media, the answer will not fulfil the purpose since the media will load before it intersects with the viewport.不幸的是,如果您的目标是使用交集观察器延迟加载媒体,那么答案将无法实现目的,因为媒体将在与视口相交之前加载。 The solution is to make sure it is the containing element of the media that is being observed, instead the element on which display none is being applied.解决方案是确保它是被观察的媒体的包含元素,而不是应用显示 none 的元素。

https://codesandbox.io/s/react-lazyload-forked-yz93f?file=/src/LazyLoad.js:0-958 https://codesandbox.io/s/react-lazyload-forked-yz93f?file=/src/LazyLoad.js:0-958

import React, { Component, createRef } from "react";

import "./styles.css";

class LazyLoad extends Component {
  observer = null;
  rootRef = createRef();
  state = {
    intersected: false
  };

  componentDidMount() {
    this.observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (entry.isIntersecting) {
          this.setState({ intersected: true });
          this.observer.disconnect();
        }
      },
      { root: null, threshold: 0.2 }
    );
    this.observer.observe(this.rootRef.current);
    console.log(this.rootRef);
  }

  render() {
    return (
      <div className="outer" ref={this.rootRef}>
        <span>{JSON.stringify(this.state.intersected)}</span>
        <div
          className={`container ${
            this.state.intersected ? "d-block" : "d-none"
          }`}
        >
          {this.props.children}
        </div>
      </div>
    );
  }
}

export default LazyLoad;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM