以前看視頻學習聽到這個offset()感覺很陌生,沒有用過,馬上記到筆記里了,今天翻起筆記再次看到,都已經忘記是怎么用的了,所以來到這里狠狠的記下來:
offset() 方法返回得或設置元素相對於文檔的偏移(位置)。一般情況下有兩個值:top和left值,經測試,不管所選的元素在哪偏移都是從整個文檔開始算的
粘貼下面的代碼,看效果
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> <title>測試偏移是從哪開始的</title> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js"></script> <style type="text/css"> .box1{height: 300px;} .box2{padding: 10px;border: 1px solid #ddd;} </style> </head> <body> <div class="box1"></div> <div class="box2"> <p>代碼征服世界 本段文字偏移left<span></span>,top<strong></strong></p> </div> <script type="text/javascript"> $(document).ready(function(){ var x=$("p").offset(); $("span").text(x.left); $("strong").text(x.top); }); </script> </body> </html>