四個按鈕,分別增加/減少寬度與高度,每次增減 50px。範例刻意把 id 字串拆開拼接("#addwidthke" + "leyi"),這是為了避免與站內某些關鍵字比對衝突,實際寫專案時正常書寫即可。
效果體驗:https:///keleyi/phtml/jquery/23.htm
<div>
<input id="addwidthkeleyi" value="增加寬度" type="button" />
<input id="reducewidthkeleyi" value="減少寬度" type="button" />
<input id="addheightkeleyi" value="增加高度" type="button" />
<input id="reduceheightkeleyi" value="減少高度" type="button" />
</div>
<div style="border:1px solid #999;width:200px;height:200px" id="keleyidiv"></div>
<script type="text/javascript">
$("#addwidthkeleyi").on("click", function () {
$("#keleyidiv").width($("#keleyidiv").width() + 50);
});
$("#reducewidthkeleyi").on("click", function () {
$("#keleyidiv").width($("#keleyidiv").width() - 50);
});
$("#addheightkeleyi").on("click", function () {
$("#keleyidiv").height($("#keleyidiv").height() + 50);
});
$("#reduceheightkeleyi").on("click", function () {
$("#keleyidiv").height($("#keleyidiv").height() - 50);
});
</script>
width() 不只是「設定」,不帶參數呼叫時是「取得」,回傳不含 padding、border、margin 的數字(單位為 px)。因此 $(x).width($(x).width() + 50) 這種自我參照的寫法完全成立。
innerWidth();含 border 用 outerWidth();連 margin 一起算則是 outerWidth(true)。Math.max(50, w - 50)。.animate({ width: w }, 300) 即可。