簡體   English   中英

在iframe中找出html元素的位置

[英]FInd out position of html element in iframe

我想找出iframe中元素的位置。 我正在嘗試使用: -

//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 };  
}

要獲取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);

但這不起作用。 最初elem不為null,但elem.offsetParent在每種情況下都為null。 我做錯了嗎?

對於某些元素,它工作正常。 但對於某些元素,offsetParent將為null,因此其offsetLeft為0且offetTop為0。

有沒有其他方法可以找出每個元素的位置。

提前致謝..

您似乎已經在使用jQuery。 為什么不讓jQuery為你做繁重的工作呢?

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM