国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

javascript獲取隱藏dom的寬高 具體實現(xiàn)

2024-05-06 15:49:07
字體:
來源:轉載
供稿:網友
一個隱藏的DOM是獲取不到寬高的,如果想要獲取,采用下面的方法:

首先clone一個DOM,設置position:absolute,然后設置top為一個比較大的負值,然后使其顯示出來,最后獲取到了DOM的寬高后,將其remove。
具體代碼如下:
Js代碼

復制代碼 代碼如下:


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));
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));


還有其他更好的方法歡迎提出來。
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 兴海县| 镇赉县| 东丽区| 密山市| 舞钢市| 织金县| 龙游县| 阿勒泰市| 澄江县| 谢通门县| 郓城县| 凤翔县| 高雄市| 成安县| 琼海市| 东乡县| 张家口市| 金塔县| 永嘉县| 札达县| 仙桃市| 镇安县| 方正县| 弥渡县| 祁门县| 南川市| 轮台县| 三亚市| 岐山县| 攀枝花市| 巴林左旗| 临沧市| 宁远县| 德阳市| 获嘉县| 洮南市| 固始县| 都兰县| 子洲县| 梁河县| 马山县|