DIV CSS 佈局教程網

用 jQuery 取得含 margin 的 outerWidth 與 outerHeight
編輯:JQuery特效代碼     

本文示範如何使用 jQuery 的 outerWidth(true) 與 outerHeight(true),取得包含 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) - 回傳元素寬度(含 padding、border 與 margin)。</p>
<p>outerHeight(true) - 回傳元素高度(含 padding、border 與 margin)。</p>
</body>
</html>

關鍵在傳入參數 true:不傳或傳 false 時只含 padding 與 border,傳 true 才會把 margin 一併計入。希望本文對大家的 jQuery 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved