How to determine when an HTML5 element has been viewed?

前端 未结 4 1705
小鲜肉
小鲜肉 2020-12-10 09:21

I am wondering if there are any HTML5 events associated with whether or not an element has been viewed or \"scrolled into view\" by the user.

An example could be a l

4条回答
  •  借酒劲吻你
    2020-12-10 09:53

    In plain JavaScript you can use the event "scroll" along with getBoundingClientRect().bottom <= window.innerHeight to determine if an html element has come into view.

    document.addEventListener("scroll", inView);
    
    function inView() {
        if (document.getElementById("viewElement").getBoundingClientRect().bottom <= window.innerHeight) {
            console.log("in view");
            // uncomment below if you only want it to notify once
            // document.removeEventListener("scroll", inView);
        }
    }
    

    The console prints "in view" when the element comes into view.

    Hello there!

提交回复
热议问题