09-解决方案
6.2.2 解决方案
width
和 height
方法可以应用到任何元素,它们都能用于确定元素的宽度或者高度。但是如果需要确定元素在屏幕上实际占据的空间,它们就力不能及了。除了width和height之外,jQuery还提供了如下用于确定元素更具体尺寸的方法:
innerWidth
返回不包含边框但包含内边距的宽度。
innerHeight
返回不包含边框但包含内边距的高度。
outerWidth
返回包括边框和内边距的宽度。
outerHeight
返回包含边框和内边距的高度。
图6-2是视觉参考。
假定有如下HTML:
<div id="results"></div>
<div id="myDiv">Some text.</div>
和下面的CSS:
#myDiv {
width:100px;
height:30px;
padding:10px;
border:1px;
}
你可以预期下面的代码:
jQuery(document).ready(function() {
var $myDiv = jQuery('#myDiv');
var $results = jQuery('#results');
jQuery('<p>Computed width: ' + $myDiv.width() + '</p>')
.appendTo($results); // 100
jQuery('<p>Computed height: ' + $myDiv.height() + '</p>')
.appendTo($results); // 30
jQuery('<p>Inner width: ' + $myDiv.innerWidth() + '</p>')
.appendTo($results); // 120
jQuery('<p>Inner height: ' + $myDiv.innerHeight() + '</p>')
.appendTo($results); // 50
jQuery('<p>Outer width: ' + $myDiv.outerWidth() + '</p>')
.appendTo($results); // 122
jQuery('<p>Outer height: ' + $myDiv.outerHeight() + '</p>')
.appendTo($results); // 52
jQuery('<p>Document outer height: ' + jQuery(document).outerHeight() + '</p>')
.appendTo($results); // NaN
jQuery('<p>Document inner height: ' + jQuery(document).innerHeight() + '</p>')
.appendTo($results); // NaN
jQuery('<p>Window outer height: ' + jQuery(window).outerHeight() + '</p>')
.appendTo($results); // NaN
jQuery('<p>Window inner height: ' + jQuery(window).innerHeight() + '</p>')
.appendTo($results); // NaN
});