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

问题描述 投票:27回答:2

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

我该怎么做?

实际上,我可以找到元素的窗口偏移量,但它从元素的边框检索坐标,如下所示:

var _position = $(this).offset();
javascript jquery coordinates center offset
2个回答
61
投票

您必须使用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;

如果需要在计算中考虑填充属性,请使用以下命令:

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

9
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.