簡體   English   中英

了解偏移方法的返回值

[英]Understanding the offset method's return values

我在HTML文檔中有一個id="stimulus"的元素。

當我在瀏覽器中打開此文檔並使用瀏覽器控制台調查#stimulus屬性時,這就是我所看到的:

> $('#stimulus').offset()
< Object {top: 0, left: 0}
> $('#stimulus').css('top')
< "-155.761px"
> $('#stimulus').css('left')
< "253.087px"

我怎么解釋這個? offset內的top使用css方法訪問的top有何不同?

offset()文檔中 ,offset來自文檔的頂部; 而top和left css屬性是相對於父級的。 也許您希望查看position( )以獲得相對於偏移父項偏移量

偏移是整個頁面中的位置

css top將相對於它最近的祖先位置放置元素。 祖先可以在頁面中的任何位置,因此偏移和頂部不匹配,除非沒有定位的祖先

你可能得到了結果的差異,因為id="stimulus"正在動畫,你在不同的幀中發送了console.log 或者元素實際上是“靜態的”並且具有一些其他屬性來改變他的offset()位置。

喜歡

 console.log("Offset:", $('.test').offset()); // returns {top: 0, left: 0} console.log("Top/Left:", $('.test').css('top'), $('.test').css('left')); // returns -200px, -20px 
 .test{ position: absolute; top: -200px; left: -20px; transform: translateY(200px) translateX(20px); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test"></div> 

jQuery的.offset()方法“返回元素相對於文檔的坐標”,而.css()方法返回通過CSS樣式應用的任何值。

http://api.jquery.com/offset/

來自jQuery的.offset()文檔

.offset()方法允許我們檢索元素相對於文檔的當前位置。 將此與.position()對比,該位置檢索相對於偏移父項的當前位置。

.css()方法抽象原生CSSStyleDeclaration API ,它返回相對於父元素的位置, 但前提是它在CSS中顯式指定 所以如果你想要那個,那么使用.position()而不是.offset()

演示

 $(function() { var child = $('.child'); console.log('offset: ', child.offset()); console.log('position: ', child.position()); console.log('css: ', { top: child.css('top'), left: child.css('left') }); }); 
 html, body { margin: 0; padding: 0; } .parent { position: absolute; top: 5px; left: 5px; } .child { position: absolute; top: 10px; left: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- results pane console output; see http://meta.stackexchange.com/a/242491 --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script> <div class="parent"> <div class="child">Hello World</div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM