JQ height()、innerHeight()、outerHeight()函数的差异
JQ height()、innerHeight()、outerHeight()函数的区别
在jQuery中,获取元素高度的函数有3个,它们分别是height()、 innerHeight()、 outerHeight()。
与此相对应的是,获取元素宽度的函数也有3个,它们分别是width()、 innerWidth()、 outerWidth()。
在这里,我们以height()、innerHeight()、outerHeight()3个函数为例,来详细介绍它们之间的区别。
下面我们以元素box的盒模型为例来介绍它们之间的区别。
height():height
innerHeight():height + padding
outerHeight():height + padding + border
outerHeight(true):height+padding+border+margin
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="jquery-1.10.1.min.js"></script> </head> <body> <div id="box" style="margin:5px; padding:10px; width:100px; height:100px; border:1px solid #000;"></div> <script> var $ele = $("#box"); // height() = height(100) = 100 document.writeln( $ele.height() ); // 100 // innerHeight() = height(100) + padding(10*2)= 120 document.writeln( $ele.innerHeight() ); // 120 // outerHeight() = height(100) + padding(10*2) + border(1*2) = 122 document.writeln( $ele.outerHeight() ); // 122 // outerHeight(true) = height(100) + padding(10*2) + border(1*2) + margin(5*2) = 132 document.writeln( $ele.outerHeight(true) ); // 132 </script> </body> </html>
效果图: