Javascript 如何找到元素的x中心坐标和相关的窗口偏移量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8027875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:26:31  来源:igfitidea点击:

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

javascriptjquerycoordinatescenteroffset

提问by itsme

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

我想从他自己的 x 中心坐标开始检索元素偏移量。

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();

回答by Rob W

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.

您必须使用offset()获取顶部和左侧位置,然后将height()width()值的一半添加到它们。这给出了中心坐标。

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:

如果您需要在计算中考虑 padding 属性,请使用以下内容:

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

回答by Strategist

This can now be done through native Javascript also:

这现在也可以通过本机 Javascript 完成:

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.

其中 targetNode 是您想要获取其中心坐标的元素。