jQuery獲取網頁中的元素距離文件邊緣的距離程式碼例項

admin發表於2017-03-31

本章節介紹一下如何獲取指定元素距離文件邊緣的距離,有需要的朋友可以做一下參考。

程式碼例項:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>  
<html>  
<head>  
<meta charset=" utf-8">  
<meta name="author" content="http://www.softwhy.com/" />  
<title>螞蟻部落</title> 
<style type="text/css">  
#antzone{  
  width:100px;  
  height:100px;  
  background-color:green; 
  margin:100px;
  text-align:center;
  line-height:100px;
}  
</style>  
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<script type="text/javascript">  
$(document).ready(function(){
   function getDistance(obj){  
    if(!obj instanceof jQuery){  
     obj=$(obj);  
    }  
    var distance={};  
    distance.top=(obj.offset().top-$(document).scrollTop());  
    distance.bottom=($(window).height()-distance.top-obj.outerHeight());  
    distance.left=(obj.offset().left-$(document).scrollLeft());  
    distance.right=($(window).width()-distance.left-obj.outerWidth());  
    return distance;  
  }
  $("#antzone").text(getDistance($("#antzone")).left);
})
</script>  
</head>  
<body>  
<div id="antzone"></div>  
</body>  
</html>

上面的程式碼實現了我們的要求,下面介紹一下它的實現過程。

一.程式碼註釋:

(1).$(document).ready(function(){}),當文件結構完全載入完畢再去執行函式中的程式碼。

(2).function getDistance(obj){},此函式實現了獲取元素距離文件邊緣的距離(準確的說是距離瀏覽器客戶區邊緣的距離),引數可以是jquery物件也可以是dom物件。

(3).if(!obj instanceof jQuery){

  obj=$(obj);

} 判斷是否是jquery物件,如果不是則轉換為jquery物件。

(4).var distance={},建立一個物件直接量,從來儲存距離客戶區邊緣的距離。

(5).distance.top=(obj.offset().top-$(document).scrollTop()),獲取距離客戶區頂部的距離。

(6).distance.bottom=($(window).height()-distance.top-obj.outerHeight()),獲取元素距離客戶區底部的距離。

二.相關閱讀:

(1).instanceof可以參閱javascript instanceof一章節。

(2).offset()方法可以參閱jQuery offset()一章節。

(3).scrollTop()方法可以參閱jQuery scrollTop()一章節。

(4).outerHeight可以參閱jquery outerHeight()一章節。

相關文章