Play HTML5 Video when scrolled to

前端 未结 4 2281
暖寄归人
暖寄归人 2020-12-02 17:14

Is there anyway to autoplay a HTML5 video only when the user has the video (or a certain percentage of the video) in the browser viewport?

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-02 17:58

    There is a new API for this scenario, called Intersection_Observer_API, which Chrome 51+ and Edge 15+ has supported.

    var options = {
        root: document.querySelector('.scroll-container'),
        rootMargin: '0px',
        threshold: 1.0 // trigger only when element comes into view completely
    };
    var ob = new IntersectionObserver((entries, observer) => {
        entries[0].target.classList.toggle('red');
    }, options);
    
    // observe all targets, when coming into view, change color
    document.querySelectorAll('.target').forEach((item) => {
        ob.observe(item);
    });
    

    Here is a simple demo: https://codepen.io/hectorguo/pen/ybOKEJ

提交回复
热议问题