如何在不使用事件的情况下获取元素的pageX和pageY [英] How to get the pageX and pageY of an Element without using event

查看:157
本文介绍了如何在不使用事件的情况下获取元素的pageX和pageY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反正没有使用e.pageX和e.pageY来定位任何元素。

Is there anyway to the positioning of any element without using e.pageX and e.pageY.

检查此小提琴

小提琴实际上是一个很差的尝试,但我认为一个视觉例子会更好。我想知道的是,是否可以通过引用使用

The fiddle is actually a poor attempt at what im trying to ask, but i though a visual example would be better. What i want to know is, Is it possible to find the X and Y co-ordinates of any element on the DOM by referencing using

 document.getElementByID('elementID');

或者可能

or maybe

document.getElementsByTagName('TagName');

编辑:虽然我在FIDDLE中使用了Jquery,一个可能的解决方案只使用JavaScript。

Although i have used Jquery in the FIDDLE, I would like a possible solution using only JavaScript.

推荐答案

您可以使用

You may use

document.getElementById("elementID").offsetTop;
document.getElementById("elementID").offsetLeft;

参考 MDN 。它们返回父元素的偏移量。如果您需要元素相对于整个身体的偏移量,则可能会变得更加棘手,因为您必须对链中每个元素的偏移进行求和。

分别为 .getElementsByTagName ,因为DOM中的每个对象都具有这些属性。

Refer to MDN. They return the offset from the parent element. If you need the offset of the element in respect to the whole body it may get more tricky, as you will have to sum the offsets of each element in the chain.
Respectively for .getElementsByTagName, as each object in the DOM has these attributes.

.getBoundingClientRect 也是值得一看

var clientRectangle = document.getElementById("elementID").getBoundingClientRect();
console.log(clientRectangle.top); //or left, right, bottom

这篇关于如何在不使用事件的情况下获取元素的pageX和pageY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆