前面我們用 width()/height() 取的是內容尺寸,但如果想把 padding、border 甚至 margin 都算進去,該怎麼辦?這就要用 outerWidth() 和 outerHeight() 了。本文用實例說明。
關鍵:那個布爾參數
outerWidth(true)/outerHeight(true) 中的 true 表示「把 margin 也包含進來」。若傳 false 或不傳,則只計算 padding 與 border,不含 margin。
代碼示例
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("button").click(function(){
var txt="";
txt+="Width of div: " + $("#div1").width() + "</br>";
txt+="Height of div: " + $("#div1").height() + "</br>";
txt+="Outer width of div (margin included): " + $("#div1").outerWidth(true) + "</br>";
txt+="Outer height of div (margin included): " + $("#div1").outerHeight(true);
$("#div1").html(txt);
}); </script>
</head>
<body>
<div id="div1" style="height:100px;width:300px;padding:10px;margin:3px;border:1px solid blue;background-color:lightblue;"> </div>
<br>
<button>Display dimensions of div</button>
<p>outerWidth(true) - returns the width of an element (includes padding, border, and margin).</p>
<p>outerHeight(true) - returns the height of an element (includes padding, border, and margin).</p>
</body>
</html>
三者對比
簡單記:width() 只有內容;outerWidth() 加上 padding 和 border;outerWidth(true) 再加上 margin。做元素間距計算時,這個區別尤其重要。
希望本文對你的 jQuery 程序設計有所幫助。