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

首頁 > 編程 > JavaScript > 正文

javascript獲取隱藏dom的寬高 具體實現

2019-11-20 22:31:31
字體:
來源:轉載
供稿:網友
首先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));

還有其他更好的方法歡迎提出來。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 天柱县| 宿州市| 玉环县| 宁城县| 蒙阴县| 高唐县| 江永县| 唐河县| 嘉兴市| 湄潭县| 二连浩特市| 乌拉特后旗| 达州市| 视频| 乐安县| 五莲县| 龙口市| 武城县| 比如县| 安陆市| 文水县| 若羌县| 茂名市| 阳曲县| 郴州市| 邢台县| 南江县| 离岛区| 弥勒县| 石林| 清丰县| 九龙坡区| 前郭尔| 乌兰察布市| 绥江县| 绥棱县| 蕲春县| 东兰县| 新乡市| 禄丰县| 宜兴市|