一個隱藏的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 =
px
;
nDom
style
display =
block
;
document
getElementsByTagName(
body
)[
]
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:
;width:
px;height:
px;position:absolute;display:none;";
domA
setAttribute("style"
_ostyle);
domA
style
cssText = _ostyle;
domA
setAttribute("href"
"javascript:void(
);");
document
getElementsByTagName(
body
)[
]
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 =
px
;
nDom
style
display =
block
;
document
getElementsByTagName(
body
)[
]
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:
;width:
px;height:
px;position:absolute;display:none;";
domA
setAttribute("style"
_ostyle);
domA
style
cssText = _ostyle;
domA
setAttribute("href"
"javascript:void(
);");
document
getElementsByTagName(
body
)[
]
appendChild(o);
console
log(getWH(domA));
還有其他更好的方法歡迎提出來
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/20102.html