js监听滚动条判断dom元素是否在屏幕可视范围(个人笔记)

45 阅读1分钟

需求:页面存在video标签,需要在video完全展示的时候才开始播放

    var video = document.getElementById('video');
    function isContain(dom) {
        const totalHeight = window.innerHeight || document.documentElement.clientHeight;
        const totalWidth = window.innerWidth || document.documentElement.clientWidth;
        const { top, right, bottom, left } = dom.getBoundingClientRect();
        return (top >= 0 && left >= 0 && right <= totalWidth && bottom <= totalHeight);
    }

   window.addEventListener("scroll", function () {
       let is = isContain(video)
       console.log(is, video.paused);
        if(is&&video.paused){
              video.play();
              console.log('播放');
        }
        if(!is && !video.paused){
            video.pause()
              console.log('暂停');
        }
    })