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


jQuery 中的寬度

寬度是容器的水平度量,例如 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:400px;padding:20px;margin:1px;border:1px solid red; background-color:gray;"></div><br>
<button>Get Width of div</button>

</body>
</html>

jQuery 中的 innerWidth

innerWidth() 返回第一個匹配元素的內部寬度。 它包括填充,但不包括邊框和邊距。

示例

你可以執行以下程式碼在 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("Inner Width of div element: " + $("div").innerWidth());
    });
});
</script>
</head>
<body>

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

</body>
</html>

更新於: 17-12-2019

208 瀏覽

啟動你的 職業

完成課程獲得認證

開始
廣告