熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

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

2022-06-13   來源: JSP教程 
一個隱藏的DOM是獲取不到寬高的如果想要獲取采用下面的方法  

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

復制代碼 代碼如下:
function getCss(elem css){ 
 if (windowgetComputedStyle) { 
  return windowgetComputedStyle(elem null)[css]; 
 }else if (elemcurrentStyle) { 
  return elemcurrentStyle[css]; 
 }else { 
  return elemstyle[css]; 
 } 

function getWH(dom){ 
 var get = function(elem){ 
  var wh = {}; 
  Width Heightreplace(/[^ ]+/g function(i){ 
   var a = itoLowerCase(); 
   wh[a] = elem[offset + i] || elem[client + i]; 
  }); 
  return wh; 
 }; 
 if (getCss(dom display) === none) { 
  var nDom = domcloneNode(true); 
  nDomstyleposition = absolute
  nDomstyletop = px
  nDomstyledisplay = block
  documentgetElementsByTagName(body)[]appendChild(nDom); 
  var wh = get(nDom); 
  nDomparentNoderemoveChild(nDom); 
  return wh; 
 }  
 return get(dom); 

//test  
consolelog(getWH(documentgetElementById(content))); 
var domA = documentcreateElement("a") _ostyle = "position:absolute;zindex:;width:px;height:px;position:absolute;display:none;"; 
domAsetAttribute("style" _ostyle); 
domAstylecssText = _ostyle; 
domAsetAttribute("href" "javascript:void();"); 
documentgetElementsByTagName(body)[]appendChild(o); 
consolelog(getWH(domA));
function getCss(elem css){
 if (windowgetComputedStyle) {
  return windowgetComputedStyle(elem null)[css];
 }else if (elemcurrentStyle) {
  return elemcurrentStyle[css];
 }else {
  return elemstyle[css];
 }
}
function getWH(dom){
 var get = function(elem){
  var wh = {};
  Width Heightreplace(/[^ ]+/g function(i){
   var a = itoLowerCase();
   wh[a] = elem[offset + i] || elem[client + i];
  });
  return wh;
 };
 if (getCss(dom display) === none) {
  var nDom = domcloneNode(true);
  nDomstyleposition = absolute;
  nDomstyletop = px;
  nDomstyledisplay = block;
  documentgetElementsByTagName(body)[]appendChild(nDom);
  var wh = get(nDom);
  nDomparentNoderemoveChild(nDom);
  return wh;
 }
 return get(dom);
}
//test
consolelog(getWH(documentgetElementById(content)));
var domA = documentcreateElement("a") _ostyle = "position:absolute;zindex:;width:px;height:px;position:absolute;display:none;";
domAsetAttribute("style" _ostyle);
domAstylecssText = _ostyle;
domAsetAttribute("href" "javascript:void();");
documentgetElementsByTagName(body)[]appendChild(o);
consolelog(getWH(domA));

  
還有其他更好的方法歡迎提出來


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20102.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.