figure element size using javascript

 1  //get element size
 2 
 3     function getElementLeft(element) {
 4         var actualLeft = element.offsetLeft;
 5         var current = element.offsetParent;
 6 
 7         while (current !== null) {
 8             actualLeft += current.offsetLeft;
 9             current = current.offsetParent;
10         }
11 
12         return actualLeft;
13     }
14 
15     function getElementTop(element) {
16         var actualTop = element.offsetTop;
17         var current = element.offsetParent;
18 
19         while (current !== null) {
20             actualTop += current.offsetTop;
21             current = current.offsetParent;
22         }
23 
24         return actualTop;
25     }
26 
27     function getViewport() {
28         if (document.compatMode == "BackCompat") {
29             return {
30                 width: document.body.clientWidth,
31                 height: document.body.clientHeight
32             };
33         } else {
34             return {
35                 width: document.documentElement.clientWidth,
36                height:document.documentElement.clientHeight
37             };
38         }
39    }
40    
41    function getBoundingClientRect(element) {
42        var scrollTop = document.documentElement.scrollTop;
43        var scrollLeft = document.documentElement.scrollLeft;
44 
45        if (element.getBoundingClientRect) {
46            if (typeof arguments.callee.offset != "number") {
47                var temp = document.createElement("div");
48                temp.style.cssText = "position:absolute;left:0;top:0;";
49                document.body.appendChild(temp);
50                arguments.callee.offset = -temp.getBoundingClientRect().top - scrollTop;
51                document.body.removeChild(temp);
52                temp = null;
53            }
54 
55            var rect = element.getBoundingClientRect();
56            var offset = arguments.callee.offset;
57 
58            return {
59                left: rect.left + offset,
60                right: rect.right + offset,
61                top: rect.top + offset,
62                bottom: rect.bottom + offset
63            };
64        } else {
65 
66            var actualLeft = getElementLeft(element);
67            var actualTop = getElementTop(element);
68 
69            return {
70                left: actualLeft - scrollLeft,
71                right: actualLeft + element.offsetWidth - scrollLeft,
72                top: actualTop - scrollTop,
73                bottom:actualTop+element.offsetHeight-scrollTop
74            };
75        }
76    }

 

posted on 2013-05-15 21:05  雷音  阅读(185)  评论(0编辑  收藏  举报

导航