简体   繁体   English

在iframe中找出html元素的位置

[英]FInd out position of html element in iframe

I want to find out the position of an element which is in iframe. 我想找出iframe中元素的位置。 I am trying ot use:- 我正在尝试使用: -

//Function to find the position of element on page
function getElementPosition(elem){
  var posX = 0;
  var posY = 0;
  while(elem!= null){  
        posX += elem.offsetLeft;  
        posY += elem.offsetTop;  
        elem = elem.offsetParent;
    console.log("In function:" + elem.tagName + " " + posX + " " + posY);
  }                              
 return { x : posX, y : posY };  
}

To get the list of all elements of iframe, 要获取iframe的所有元素的列表,

var doc1 = $('#page1').get(0).contentDocument; // page1 is id of iframe element
var list1 = doc1.getElementsByTagName('*');
console.log(list1.length);                     // Printing correctly
var index = prompt("Enter element index");
var elem1 = list1[index];
var pos1 = getElementPosition(elem1);
console.log("Positions:" + pos1.x + " " + pos1.y);

But this is not working. 但这不起作用。 Initially elem is not null but elem.offsetParent is null in every case. 最初elem不为null,但elem.offsetParent在每种情况下都为null。 Am i doing some wrong ? 我做错了吗?

For some elements, it is working fine. 对于某些元素,它工作正常。 But for some elements, offsetParent is coming null and so their offsetLeft is 0 and offetTop is 0. 但对于某些元素,offsetParent将为null,因此其offsetLeft为0且offetTop为0。

Is there any other way to find out position of each element. 有没有其他方法可以找出每个元素的位置。

Thanks in advance.. 提前致谢..

You already appear to be using jQuery. 您似乎已经在使用jQuery。 Why not let jQuery do the heavy lifting for you? 为什么不让jQuery为你做繁重的工作呢?

http://api.jquery.com/position/ http://api.jquery.com/position/

http://api.jquery.com/offset/ http://api.jquery.com/offset/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM