javascript獲取隱藏dom的寬高【轉】

 

一個隱藏的DOM是獲取不到寬高的,若是想要獲取,採用下面的方法:
首先clone一個DOM,設置position:absolute,而後設置top爲一個比較大的負值,而後使其顯示出來,最後獲取到了DOM的寬高後,將其remove。 javascript

具體代碼以下: php

 

function getCss(elem, css){
 if (window.getComputedStyle) {
  return window.getComputedStyle(elem, null)[css];
 }else if (elem.currentStyle) {
  return elem.currentStyle[css];
 }else {
  return elem.style[css];
 }
}
function getWH(dom){
 var get = function(elem){
  var wh = {};
  'Width Height'.replace(/[^ ]+/g, function(i){
   var a = i.toLowerCase();
   wh[a] = elem['offset' + i] || elem['client' + i];
  });
  return wh;
 };
 if (getCss(dom, 'display') === 'none') {
  var nDom = dom.cloneNode(true);
  nDom.style.position = 'absolute';
  nDom.style.top = '-3000px';
  nDom.style.display = 'block';
  document.getElementsByTagName('body')[0].appendChild(nDom);
  var wh = get(nDom);
  nDom.parentNode.removeChild(nDom);
  return wh;
 } 
 return get(dom);
}
//test 
console.log(getWH(document.getElementById('content')));
var domA = document.createElement("a"), _ostyle = "position:absolute;z-index:999999;width:92px;height:22px;position:absolute;display:none;";
domA.setAttribute("style", _ostyle);
domA.style.cssText = _ostyle;
domA.setAttribute("href", "javascript:void(0);");
document.getElementsByTagName('body')[0].appendChild(o);
console.log(getWH(domA));
 

 

還有其餘更好的方法歡迎提出來。 css

 

原文地址:http://blogread.cn/it/article.php?id=4492&f=sinat java

相關文章
相關標籤/搜索