Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to determine when an HTML5 element has been viewed?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

<div id="viewElement">Hello there!</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...