Event listener for when element becomes visible?

后端 未结 9 2076
感情败类
感情败类 2020-11-28 05:36

I am building a toolbar that is going to be included into a page. the div it is going to be included in will default to display:none. Is there a way i can p

9条回答
  •  情歌与酒
    2020-11-28 06:12

    Going forward, the new HTML Intersection Observer API is the thing you're looking for. It allows you to configure a callback that is called whenever one element, called the target, intersects either the device viewport or a specified element. It's available in latest versions of Chrome, Firefox and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API for more info.

    Simple code example for observing display:none switching:

    // Start observing visbility of element. On change, the
    //   the callback is called with Boolean visibility as
    //   argument:
    
    respondToVisibility(element, callback) {
      var options = {
        root: document.documentElement
      }
    
      var observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
          callback(entry.intersectionRatio > 0);
        });
      }, options);
    
      observer.observe(element);
    }
    

    In action: https://jsfiddle.net/elmarj/u35tez5n/5/

提交回复
热议问题