jQuery outerWidth() 方法用于返回第一个匹配的元素的外部宽度,带有填充和边框。

jQuery outerWidth () 方法适用于可见和隐藏元素。

jQuery outerWidth() 方法

在上图中,你可以看到jQuery的outerWidth()方法包括border和padding。

语法

$(selector).outerWidth(includeMargin);

参数

参数说明
includeMargin

是可选参数。它是一个布尔值,指定是否包含边距。

  • false:这是一个默认值。它指定不包括边距。
  • true:指定包含边距。

例子

例1

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Outer width of div is: " + $("div").outerWidth(true));
    });
});
</script>
</head>
<body>
<div style="height:100px;width:500px;padding:10px;margin:3px;border:1px blue;background-color:lightpink;"></div><br>
<button>点击获取outerWidth</button>
</body>
</html>
例2
<!DOCTYPE html>
<html>
   <head>
      <title>jQuery outerWidth() 方法例子</title>
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
		
      <script type="text/javascript" language="javascript">
         $(document).ready(function() {
            $("div").click(function () {
               var color = $(this).css("background-color");
               var width = $(this).outerWidth( true );
               $("#result").html("Outer Width is <span>" + width + "</span>.");
               $("#result").css({'color': color, 'background-color':'white'});
            });
         });
      </script>
<style>
         #div1{ margin:10px;padding:10px; border:2px solid #666; width:60px;}
         #div2 { margin:15px;padding:15px; border:4px solid #666; width:60px;}
         #div3 { margin:20px;padding:20px; border:6px solid #666; width:60px;}
         #div4 { margin:25px;padding:25px; border:8px solid #666; width:60px;}
</style>
</head>
<body>
<p>点击任意方块:</p>
<span id="result"> </span>  
<div id="div1" style="background-color:orange;"></div>  
<div id="div2" style="background-color:green;"></div>  
<div id="div3" style="background-color:brown;"></div>  
<div id="div4" style="background-color:violet;"></div>  

</body>

</html>