這篇文章主要介紹了javascript獲取隱藏元素(display:none)的高度和寬度的方法,實現方法比較復雜,需要的朋友可以參考下
js獲取可見元素的尺寸還是比較方便的,這個可以直接使用這個方法:
function getDefaultStyle(obj,attribute){ // 返回最終樣式函數,兼容IE和DOM,設置參數:元素對象、樣式特性
return obj.currentStyle?obj.currentStyle[attribute]:document.defaultView.getComputedStyle(obj,false)[attribute];
}
但是如果這個元素是隱藏(display:none)的,尺寸又是未知自適應的,哪有上面的方法就不行了!因為display:none的元素是沒有物理尺寸的! 悲劇就這樣發生了!
解決思路:
1. 獲取元素(拿寬高那個)所有隱藏的祖先元素直到body元素,包括自己。
2. 獲取所有隱藏元素的style的display、visibility 屬性,保存下來。
3. 設置所有隱藏元素為 visibility:hidden;display:block !important;(之所以要important是避免優先級不夠)。
4. 獲取元素(拿寬高那個)的寬高。
5. 恢復所有隱藏元素的style的display、visibility 屬性。
6. 返回元素寬高值。
代碼實現:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
|
function
getSize(id){
var
width,
height,
elem = document.getElementById(id),
noneNodes = [],
nodeStyle = [];
getNoneNode(elem);
//獲取多層display:none;的元素
setNodeStyle();
width = elem.clientWidth;
height = elem.clientHeight;
resumeNodeStyle();
return
{
width : width,
height : height
}
function
getNoneNode(node){
var
display = getStyles(node).getPropertyValue(
'display'
),
tagName = node.nodeName.toLowerCase();
if
(display !=
'none'
&& tagName !=
'body'
){
getNoneNode(node.parentNode);
}
else
{
noneNodes.push(node);
if
(tagName !=
'body'
)
getNoneNode(node.parentNode);
}
}
//這方法才能獲取最終是否有display屬性設置,不能style.display。
function
getStyles(elem) {
// Support: IE<=11+, Firefox<=30+ (#15098, #14150)
// IE throws on elements created in popups
// FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
var
view = elem.ownerDocument.defaultView;
if
(!view || !view.opener) {
view = window;
}
return
view.getComputedStyle(elem);
};
function
setNodeStyle(){
var
i = 0;
for
(; i < noneNodes.length; i++){
var
visibility = noneNodes[i].style.visibility,
display = noneNodes[i].style.display,
style = noneNodes[i].getAttribute(
"style"
);
//覆蓋其他display樣式
noneNodes[i].setAttribute(
"style"
,
"visibility:hidden;display:block !important;"
+ style);
nodeStyle[i] = {
visibility :visibility,
display : display
}
}
}
function
resumeNodeStyle(){
var
i = 0;
for
(; i < noneNodes.length; i++){
noneNodes[i].style.visibility = nodeStyle[i].visibility;
noneNodes[i].style.display = nodeStyle[i].display;
}
}
}
|
注意事項:
1. 打開顯示所有隱藏祖先元素,然后獲取元素的寬高值,可能在某些情況下獲取值是不正確的。
PS:不過這個不用擔心,真正出錯時再hack方法就行。
2. 之所以要保存隱藏祖先元素display、visibility 屬性,是為了后面可以設置回來,不影響其本身。
3. 另外getStyles方法是從jquery源碼中摘取出來,這方法才能獲取最終是否有display屬性設置。
PS:不能從style.display獲取。