0

我正在将广告延迟加载到我的网站中,并且只有当用户向下滚动足够远时才能显示它,但是当用户向上滚动时,div 就会消失。我希望这样当用户第一次看到 div 时,即使他滚动离开,广告也会出现并停留在那里。我也不希望广告令人耳目一新。我的代码是:

export const handleAds = () => {

  var myAds;

  window.addEventListener("load", function(event){
    myAds = document.querySelector("#theDiv");
    createObserver();
  },false);

  function createObserver(){
    var observer;

    var options = {
      root: null,
      rootMargin: "0px",
      threshold: 0.2
    };

    observer = new IntersectionObserver(handleIntersect, options);
    observer.observe(myAds);

  }


  function handleIntersect(entries,observer){

    for (var i = 0; i < entries.length; i++){
      if(entries[i].isIntersecting){
        //ad script
        }
      }
    }

}
4

1 回答 1

1

调用unobserve您的回调: https ://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/unobserve

function handleIntersect(entries,observer){

  for (var i = 0; i < entries.length; i++){
    if(entries[i].isIntersecting){
      //ad script
      observer.unobserve(entries[i]);
    }
  }
}
于 2019-08-11T23:08:41.770 回答