檢查element是否出現在畫面之中

Ruei Long Shen
Nov 5 · 3 min read

在許多情況下,我們必須知道當user在捲動畫面時,某個element是不是出現在畫面之中,程式才能決定要執行那些功能,典型的例子像是: 圖片的lazy load、無限scroll(infinite scrolling)…等。

使用距離判斷:

透過新增event listener 像是scrollresize ,來判斷目標element是否出現在user的畫面之中,這邊需要知道幾樣東西:

window.innerHeightHTMLElement.offsetTopwindow.pageYOffset

window.innerHeight 指的就是瀏覽器的可視高度,也就是瀏覽器顯示畫面的高度。

Keep the story going. Sign up for an extra free read.

You've completed your member preview for this month, but when you sign up for a free Medium account, you get one more story.
Already have an account? Sign in

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade