動態調整元素尺寸是頁面交互中很常見的需求。jQuery 提供了 width() 和 height() 兩個方法,讓這件事變得異常簡單。本文用實例演示。
實現方法
只需在選擇器後接上 .width() 與 .height() 並傳入目標數值,即可設置元素尺寸。下麵點擊按鈕就把 div 調整為 500×500:
代碼示例
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").width(500).height(500);
});
}); </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>Resize div</button>
</body>
</html>
小提醒
值得注意的是,width()/height() 設置的是內容區域的尺寸,不包含 padding、border。此外它們還支持鏈式寫法,像例子中那樣一氣呵成。若不傳參數,則是「獲取」而非「設置」。
希望本文對你的 jQuery 程序設計有所幫助。