2016-05-31 43 views
0

如果我知道元素的ID是‘頁腳’,我可以用如何獲得所有元素的座標

document.getElementById("footer").getBoundingClientRect(); 

獲得‘頁腳’元素座標。

有所有的代碼

var page = require('webpage').create(); 

page.open("https://stackoverflow.com/questions/18657615/how-to-render-an-html-element-using-phantomjs", function (status) { 
    if (status !== 'success') { 
     console.log('Unable to load the address!'); 
    } else { 
     window.setTimeout(function() { 
      //Heres the actual difference from your code... 
      var bb = page.evaluate(function() { 
       //return document.body.getBoundingClientRect(); 
       return document.getElementById("footer").getBoundingClientRect();  
      }); 

      page.clipRect = { 
       top: bb.top, 
       left: bb.left, 
       width: bb.width, 
       height: bb.height 
      }; 
      console.log(bb.top); 
      console.log(bb.left); 
      console.log(bb.width); 
      console.log(bb.height); 

      page.render('capture.png'); 
      phantom.exit(); 
     }, 200); 
    } 
}); 

結果是

4004.6875
632.5

我必須知道page有元素ID爲 「頁腳」 。 如果有一個未知的網頁,我不知道該網頁的任何信息。 我如何獲得所有的元素座標。

也許traversing the dom可以幫助,但我總是得到錯誤。我不知道如何正確合併代碼。

回答

1

讓我們看看我們如何能夠更改link你發現給予代碼:

function theDOMElementWalker(node) { 
    if (node.nodeType == 1) { 

     //console.log(node.tagName); 

     node = node.firstChild; 

     while (node) { 
      theDOMElementWalker(node); 
      node = node.nextSibling; 
     } 
    } 
} 

這可以很容易地擴展到DOM「複製」到自定義表示。例如:

var dom = page.evaluate(function(){ 
    var root = { children: [] }; 
    function walk(node, obj) { 
     if (node.nodeType == 1) { 

      obj.tagName = node.tagName; 
      obj.boundingClientRect = node.getBoundingClientRect(); 

      node = node.firstChild; 

      var childObj; 
      while (node) { 
       childObj = { children: [] }; 
       obj.children.push(childObj); 
       walk(node, childObj); 
       node = node.nextSibling; 
      } 
     } 
    } 

    walk(document.documentElement, root); 

    return root; 
}); 

console.log(JSON.stringify(dom, undefined, 4)); 

這裏的想法是將DOM節點及其「簡單」表示形式傳遞給walk函數。

+0

你真好。非常感謝你! –