jQuery 中 width 和 outerWidth 之間的區別是什麼?


jQuery 中的 Width

width() 是容器的水平測量值,例如 div 的寬度。它不包括內邊距、邊框或外邊距。

示例

你可以嘗試執行以下程式碼來學習如何在 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(){
    $("button").click(function(){
        alert("Width of div element: " + $("div").width());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:200px;padding:20px;margin:1px;border:1px solid red; background-color:blue;"></div><br>
<button>Get Width of div</button>

</body>
</html>

jQuery 中的 outerWidth

outerWidth() 返回第一個匹配元素的外寬度。它包括內邊距和邊框。

示例

您可以嘗試執行以下程式碼來獲取 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(){
    $("button").click(function(){
        alert("Outer Width of div element: " + $("div").outerWidth());
    });
});
</script>
</head>
<body>

<div style="height:200px;width:200px;padding:20px;margin:1px;border:1px solid red; background-color:blue;"></div><br>
<button>Get Outer Width of div</button>

</body>
</html>

更新於: 2019 年 12 月 17 日

208 次瀏覽

Kickstart 您的 職業

完成課程即可獲得認證

開始
廣告
© . All rights reserved.