【问题标题】:Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'未能在“IntersectionObserver”上执行“观察”:参数 1 不是“元素”类型
【发布时间】:2021-02-08 15:31:03
【问题描述】:

我在遵循代码星标选项时遇到错误,但它是在我的项目的最后一次运行中执行的,但实际上今天它显示“无法在 'IntersectionObserver' 上执行 'observe':参数 1 不是 'Element 类型’。”在浏览器上。

const counters = document.querySelectorAll(".counter");
  function playCounter() {
    counters.forEach((counter) => {
      counter.innerText = 0;

      let point = +counter.dataset.count;

      let step = point / 100;

      let startCount = function () {
        let displayCount = +counter.innerText;

        if (displayCount < point) {
          counter.innerText = Math.ceil(displayCount + step);
          setTimeout(startCount, 500);
        } else {
          counter.innerText = point;
        }
      };
      startCount();
    });
  }

  let counterSection = document.querySelector(".counter_wrapper");

  let scope = {
    borderMargin: "0px 0px -200px 0px",
  };
  const sectionObserver = new IntersectionObserver(function (entry) {
    if (entry[0].isIntersecting) {
      playCounter();
    }
  }, scope);
  **sectionObserver.observe(counterSection);**

【问题讨论】:

    标签: javascript html jquery reactjs


    【解决方案1】:

    其实因为document.querySelector如果元素不存在会返回null,而当element传给sectionObserver.observe()时,如果elementnull,就会抛出上面的异常发生Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element',所以请确保document.querySelector选择的元素必须存在。

    也许你可以看看这个链接。 Uncaught TypeError: Failed to execute 'observe' on 'IntersectionObserver': parameter 1 is not of type 'Element'

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2021-07-08
    • 2017-03-16
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    相关资源
    最近更新 更多