对于offset().left,top其实在网上很多说的都是迷迷糊糊的搞得人晕头转向的
所以我自己写了段代码证明一下到底是咋回事!
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> *{ padding: 0; margin: 0; border:0; } .a{ width: 400px; height: 400px; background-color: #222222; position: relative; left:100px; } .b{ width: 200px; height: 200px; background-color: blue; position: absolute; top:100px; left:50px; } .cp{ width: 50px; height: 20px; } </style> </head> <body> <div class="a"> <div class="b"> <div class="cp">hello</div> </div> </div> <script type="text/javascript" src="https://code.jquery.com/jquery-3.4.0.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(".cp").html("left"+$(".cp").offset().left+"top:"+$(".cp").offset().top); }); </script> </body> </html>
结果如下图:
然后把CSS修改为:
<style type="text/css"> .a{ width: 2400px; height: 4000px; background-color: #222222; position: relative; left:100px; } .b{ width: 200px; height: 200px; background-color: blue; position: absolute; top:1000px; left:50px; }
即对以下作出修改:
.a{
width: 2400px;
height: 4000px;
}
.b{
top:1000px;
}
结果如下:
说明是根据DOC文件来的,于当前页无关或者当前窗口无关,如果还没明白可以复杂代码操作下!