1 2 3 4 5 6 獲取元素尺寸寬高 7 8 18 19 20 Prosper 21 22 42 43 44 ...
1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>獲取元素尺寸寬高</title> 7 </head> 8 <style> 9 #div{ 10 background-color: #00ff00; 11 width: 60px; 12 height: 60px; 13 padding: 20px; 14 margin: 20px; 15 border: 20px solid #00ffff; 16 } 17 </style> 18 <body> 19 20 <div id="div">Prosper</div> 21 22 <script> 23 /** 24 * 獲取元素尺寸寬高(不包含margin) 25 */ 26 Element.prototype.getElementOffset = function () { 27 var objData = this.getBoundingClientRect(); 28 if (objData.width) { 29 return { 30 w: objData.width, 31 h: objData.height 32 } 33 } else { 34 return { 35 w: objData.right - objData.left, 36 h: objData.top - objData.bottom 37 } 38 } 39 } 40 console.log(document.getElementById('div').getElementOffset()); 41 </script> 42 </body> 43 44 </html>