【问题标题】:Execute a function when a div is visible, using the intersection observer当 div 可见时执行函数,使用交叉点观察器
【发布时间】:2021-12-27 01:14:13
【问题描述】:

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

但由于我是 javascript 新手,所以我无法成功。

如何使用交叉点观察器来做到这一点

<div id='demo'/>

我的功能

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

【问题讨论】:

  • 当你想在悬停时做某事时,为什么需要一个 Intersection Observer?
  • 喜欢延迟加载图片
  • thisthis

标签: javascript


【解决方案1】:

在观察者的回调中,检查每个观察到的条目是否相交。如果是,则调用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;
}
&lt;div id="demo"&gt;&lt;/div&gt;

【讨论】:

  • 不是鼠标悬停,必须有路口观察者
  • 当 div' 悬停时,我需要运行一个函数。 你说的没错吧?只是出于好奇,您认为 Intersection Observer 做了什么以及为什么需要它?
  • 当显示div时,该功能应该可以工作
  • 我修正了问题的标题
  • 我明白了,&lt;div&gt; 是否必须完全显示或仅部分显示才能触发 myFunc 功能?
猜你喜欢
  • 2018-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2015-05-07
  • 2022-01-11
  • 2011-05-27
相关资源
最近更新 更多