假设页面里有多个video标签。父级是.video容器。

const playVideo = () => {
  const videos = document.querySelectorAll(".video");
  for (const video of videos) {
    var bounding = video.getBoundingClientRect();
    if (bounding.top < window.innerHeight) {
      if (!video.classList.contains("played")) {
        video.classList.add("played");
        video.querySelector("video").play();
      }
    }
  }
};

window.addEventListener("DOMContentLoaded", playVideo);
window.addEventListener("scroll", playVideo);
本篇文章相关标签: