我怎么知道某个Web组件是否正在屏幕上显示?

问题描述 投票:0回答:1

我正在用小巧的方法做一个小对象,但是我想在显示一个Web组件时触发一个事件,这不仅是第一次,而且每次显示该组件时,我该怎么做?

预先感谢

web-component polymer-2.x google-web-component
1个回答
0
投票

Intersection Observer API将帮助您查找元素是否在屏幕上。有关更多信息,请visit MDN docs

// 1. Observer options
let options = {
  // The scroll area - mostly body or document
  root: document.querySelector('#parent'),
  rootMargin: '0px',
  threshold: 1.0
};

let callback = () => { /* Do something */ };

// Observe Element
let observer = new IntersectionObserver(callback, options);

// Start observing
const targetElm = document.querySelector('#target');
observer.observe(targetElm);

除IE之外,所有浏览器均支持该API,但polyfill已可用:https://github.com/w3c/IntersectionObserver

© www.soinside.com 2019 - 2024. All rights reserved.