在我們的日常開發中,經常會遇到當元素出現在可視區的時候需要去出發某一事件的情況。
我最近在優化環球網首頁的時候,將非可視區的代碼全部放入到webComponent中。打算當這個元素出現在可視區的時候去加載對應的shadowRoot。
那么,言歸正傳,對於我這個前端小白,還是好先搞定如何判斷元素出現在可視區啊!
jquery實現起來比較簡單,先解釋下幾個東東
offset().top和offsetTop;
offsetTop:元素border外側到offsetParent()的偏移量。(offsetParent():是元素的第一級擁有定位屬性(absolute/relative/fixed)的父元素).
offset().top:到document的絕對偏移量,這個當然就是我們需要的。offset().top當瀏覽器出現滾動條的時候,offset().top是不會變化的,當沒有滾動條的時候,這個值是會變化的(可以理解的哈)。
outHeight(): 元素的height+padding+border
outHeight(true):元素的height+padding+border+margin
$(window).height():瀏覽器可視窗口的高度
$(window).scrollTop():document的頂部和瀏覽器頂部的距離
所以我們就可以很簡單的判斷元素是不是出現在瀏覽器可視區了:
代碼如下(這里我故意加了個div,position為relative)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <meta charset="utf-8"> <title>js</title> <script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $(window).scroll(function () { var a = $("#eq").offset().top; console.log(a); console.log($(window).scrollTop()); console.log($(window).height()); if (a >= $(window).scrollTop() && a < ($(window).scrollTop() + $(window).height())) { console.log("div在可視范圍"); } }); }); </script> </head> <body> <div style="width:1px;height:2000px; -webkit-tap-highlight-color: transparent;">></div> <div style="position:relative"> <div id="eq" style=" width:100px; height:100px; ">1</