当div可见时,使用交集观察器执行函数

  • 本文关键字:观察 函数 执行 div javascript
  • 更新时间 :
  • 英文 :


当div出现在屏幕上时,我需要运行一个函数

但由于我是javascript的新手,我没能成功。

如何使用交叉口观察器

<div id='demo'/>

我的功能

function myFunc() {
var headID = document.getElementById("demo");         
var newScript = document.createElement('script');
newScript.src = '/myscript.js';
headID.appendChild(newScript);
}

在观察者的回调中,检查每个观察到的条目是否相互作用。如果是,则调用myFunc()并取消观察元素以只调用myFunc一次。

function myFunc() {
const script = document.createElement('script');
script.src = '/myscript.js';
demo.append(script);
console.log('Script appended');
}
/**
* This is called whenever an observed element is 
* in view or went out of view.
*/
const onIntersection = (entries, observer) => {
for (const { isIntersecting, target } of entries) {
if (isIntersecting) {
myFunc();
observer.unobserve(target);
}
}
};
/**
* The options for the observer.
* 50px 0px on the rootMargin says that the observer triggers
* after 50px in the top and bottom.
*/
const options = {
root: null,
rootMargin: '50px 0px',
threshold: [0]
};
/**
* Select the demo element, create an observer and start observing the demo element.
*/
const demo = document.getElementById('demo');
const observer = new IntersectionObserver(onIntersection, options);
observer.observe(demo);
#demo {
display: block;
height: 100px;
width: 100px;
background: red;
margin-top: 1000px;
}
<div id="demo"></div>

最新更新