How to determine when an HTML5 element has been vi

2019-01-29 05:01发布

问题:

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 longer page with elements at the bottom, which has yet to be scrolled into the users view...

I have seen jQuery solutions to this problem, however I am only interested in figuring out if weather or not this is achievable purely though the use of HTML5 events and JavaScript.

It should be noted that I have already had a look at the "onfocus" event, which (from it's official description) seems to only be applicable if the user selects or "clicks" somewhere on or within the element itself.

回答1:

As already mentioned, there is no "event" but someone already wrote a method to "detect if a DOM Element is Truly Visible" (the title). It doesn't require JQuery. You might want to check for the value on several events like the document load, scroll or window resize.



回答2:

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



回答3:

I had to do something similar to this when I built http://f1circle.com.
When the bottom banner becomes visible, I have to show a spotlight to the user asking him to login.

The code that achieves it using angularjs can be viewed at https://github.com/rajegannathan/angularUtilities/blob/master/directives/eagerload.js

Though it is an angularjs directive, the main logic is in plain javascript. Basically I check if the the last feed's bottom edge is visible and then trigger the spotlight.

I can explain more if required.