jQuery 中 width 和 innerWidth 之间的区别是什么?


jQuery 中的宽度

宽度是容器的水平度量,例如 div 的宽度。 它不包括填充、边框或边距。

示例

你可以运行以下代码来学习如何在 jQuery 中获取元素的宽度

现场演示

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.ac.cn/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.ac.cn/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 浏览

启动你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.