【问题标题】:How to find the element's x center coordinates and related window offset如何找到元素的x中心坐标和相关的窗口偏移量
【发布时间】:2011-12-23 02:16:10
【问题描述】:

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

我该怎么做?

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

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

【问题讨论】:

  • 我不确定你想要得到什么,你的元素中间的位置而不是它的最左上角?此外, $position 不是正确的语法,如果是这样,只需将 width/2 添加到 X 并将 height/2 添加到 height 就可以了。
  • @ShaiMishali 这是正确的语法。它完美地工作。只是在 JavaScript 中命名变量不是惯例。

标签: javascript jquery coordinates center offset


【解决方案1】:

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

【讨论】:

  • 你知道 width() 是否负责填充 css 规则吗?
  • 不包括padding 属性。如果您还想包含填充,请使用.outerWidth()
【解决方案2】:

这现在也可以通过原生 Javascript 来完成:

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

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

【讨论】:

  • 这只是计算相对于targetNode的OffsetParent的中心。任何具有非静态(默认)定位的父元素(一直向上)都会影响这一点。
  • 此方法返回未定义的 svg 对象
猜你喜欢
  • 2021-11-20
  • 2014-01-18
  • 2015-01-29
  • 1970-01-01
  • 2019-08-05
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 1970-01-01
相关资源
最近更新 更多