如何使用 jQuery 設定元素的寬度和高度?


若要使用 jQuery 設定元素的寬度和高度,請在 jQuery 中使用 width() 和 height()。

元素的寬度

例項

你可以嘗試執行以下程式碼以瞭解如何使用 jQuery 設定元素的寬度

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button1").click(function(){
        $("div").width(300);
    });
    $("#button2").click(function(){
        $("div").width(400);
    });
});
</script>
</head>
<body>
<div style="height:150px;width:200px;border:2px solid gray;background-color:lightblue;"></div><br>
<button id="button1">Width of div: 300</button>
<button id="button2">Width of div: 400</button><br>

</body>
</html>

元素的高度

例項

你可以嘗試執行以下程式碼以瞭解如何使用 jQuery 設定元素的高度

線上演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#button1").click(function(){
        $("div").height(250);
    });
    $("#button2").click(function(){
        $("div").height(350);
    });

});
</script>
</head>
<body>
<div style="height:150px;width:400px;border:2px solid gray;background-color:lightblue;"></div><br>
<button id="button1">Height of div: 250</button>
<button id="button2">Height of div: 350</button><br>

</body>
</html>

更新於: 2019 年 12 月 17 日

4000+ 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.