简体   繁体   中英

FInd out position of html element in iframe

I want to find out the position of an element which is in 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,

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. 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.

Is there any other way to find out position of each element.

Thanks in advance..

You already appear to be using jQuery. Why not let jQuery do the heavy lifting for you?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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