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>

更新於:17-12-2019

208 次瀏覽

職業生涯一觸即發

完成課程並獲得認證

開始
廣告