difference of top and left between Javascript and Jquery

Posted ljbguanli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了difference of top and left between Javascript and Jquery相关的知识,希望对你有一定的参考价值。

1, top and left relative to the document


jquery 
.offset()

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

var top = $(‘#elementID‘).offset().top;
var left = $(‘#elementID‘).offset().left;



native javascript
getBoundingClientRect
, top-left relative to the top-left of the viewport.

var viewportOffset = el.getBoundingClientRect();
// these are relative to the viewport
var top = viewportOffset.top;
var left = viewportOffset.left;

2, top and left relative to the parent

jquery
.position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

var topToParent = $(‘#elementID‘).position().top;
var leftToParent = $(‘#elementID‘).position().left;

native javascript

.offsetTop, .offsetLeft

The htmlElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.


var topToParent = element.offsetTop;
var leftToParent = element.offsetLeft;

3,  Border 

native javascript
element.clientTop;

The width of the top border of an element in pixels. It does not include the top margin or padding. clientTop is read-only.
see:  https://developer.mozilla.org/en-US/docs/Web/API/Element/clientTop
























以上是关于difference of top and left between Javascript and Jquery的主要内容,如果未能解决你的问题,请参考以下文章

The difference of src and href

[Banner] The number of titles and images is different

[Banner] The number of titles and images is different

[LeetCode] 1984. Minimum Difference Between Highest and Lowest of K Scores

[Nuxt] Display Vuex Data Differently in Each Page of Nuxt and Vue.js

Check time of different search methods