How to find the element's x center coordinates and related window offset

十年热恋 提交于 2019-12-18 10:34:15

问题


i would like to retrieve the element offset starting from his own x center coordinates.

how can i do it?

Actually i can find the window offset of an element but it retrieves the coordinates from the border of the element like this:

var _position = $(this).offset();

回答1:


You have to use offset() to get the top and left position, then add half of the height() and width() values to them. That gives the center coordinates.

var $this = $(this);
var offset = $this.offset();
var width = $this.width();
var height = $this.height();

var centerX = offset.left + width / 2;
var centerY = offset.top + height / 2;

If you need to consider the padding property in your calculations, use the following:

var width = $this.outerWidth();
var height = $this.outerHeight();



回答2:


This can now be done through native Javascript also:

let centerX = targetNode.offsetLeft + targetNode.offsetWidth / 2;
let centerY = targetNode.offsetTop + targetNode.offsetHeight / 2;

where targetNode is the element you want to get its center coordinates.



来源:https://stackoverflow.com/questions/8027875/how-to-find-the-elements-x-center-coordinates-and-related-window-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!