首页 > web前端 > js教程 > 正文

javascript获取隐藏dom的宽高 具体实现_javascript技巧

WBOY
发布: 2016-05-16 17:28:47
原创
1226 人浏览过

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

还有其他更好的方法欢迎提出来。
相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!