How to determine when an HTML5 element has been viewed?

前端 未结 4 1712
小鲜肉
小鲜肉 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

    There are no built-in events that tell you when an entire DOM element has become viewable/visible on the page due to scrolling or window resizing.

    The only way to do this is to keep track of resize and scroll events (which can each cause more or less of your page to be visible) and then use the scroll position and window height and DOM element positions to calculate if your entire DOM element is visible.

    Some relevant pieces of code you can either consider using or look into how they work (these tend to be jQuery-based because they are harder to share if not based on a common DOM library):

    Lazy Load Plugin for jQuery

    Element "in view" Event jQuery Plugin

    Check if Element is Visible After Scrolling - plain JS

提交回复
热议问题