• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • outerWidth()

    获取匹配元素集合中第一个元素的当前计算的外部宽度(包括填充,边框和可选的边距),或设置每个匹配元素的外部宽度

    .outerWidth([includeMargin])
    • .outerWidth([includeMargin ])
    .outerWidth(value[,includeMargin])
    • .outerWidth(value[, includeMargin ])
    • .outerWidth(function)

    .outerWidth([includeMargin ])

    获取元素集合中第一个元素的当前计算宽度值,包括padding,border和选择性的margin。(注:返回一个整数(不包含“px”)表示的值,或如果在一个空集合上调用该方法,则会返回 null。)

    .outerWidth([includeMargin ])
    • includeMargin类型: Boolean。一个布尔值,表明是否在计算时包含元素的margin值。

    返回元素的宽度,一直包括l左右 padding值,border值和可选择性的margin。单位为像素。

    如果includeMargin省略或者false,padding 和 border会被包含在计算中;如果true,margin也会被包含在计算中。

    这个方法不适用于windowdocument对象,可以使用.width()代替。

    例子

    获取一个段落的outerWidth。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      p { margin:10px;padding:5px;border:2px solid #666; }
    </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
      <p>Hello</p><p></p>
    <script>var p = $("p:first");
    $("p:last").text( "outerWidth:" + p.outerWidth()+ " , outerWidth(true):" + p.outerWidth(true) );
    </script>
     
    </body>
    </html>
    

    .outerWidth(value[, includeMargin ])

    .outerWidth(value[,includeMargin])
    • value类型: String 或者 Number一个表示像素数的数字,或一个附加了可选度量单位的数字(作为字符串)。
    • includeMargin类型: Boolean(默认值:false)一个布尔值,指示是否要为元素的边距添加新值
    .outerWidth(function)
    • function类型: Function(Integer index, Number width)返回String 或 Number返回要设置的外部宽度的函数。接收元素在集合中的索引位置和旧的外部宽度作为参数。在函数中,它引用集合中的当前元素。

    调用.outerWidth(value)时,该值可以是字符串(数字和单位)或数字。如果只为该值提供一个数字,jQuery将采用像素单位。但是,如果提供了字符串,则可以使用任何有效的CSS度量(例如100px、50%或auto)。

    例子

    第一次单击每个div时更改其外部宽度(并更改其颜色)。

    <!doctype html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>outerWidth demo</title>
      <style>
      div {
        width: 60px;
        padding: 10px;
        height: 50px;
        float: left;
        margin: 5px;
        background: red;
        cursor: pointer;
      }
      .mod {
        background: blue;
        cursor: default;
      }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
    <div>d</div>
    <div>d</div>
    <div>d</div>
    <div>d</div>
    <div>d</div>
     
    <script>
    var modWidth = 60;
    $( "div" ).one( "click", function() {
      $( this ).outerWidth( modWidth ).addClass( "mod" );
      modWidth -= 8;
    });
    </script>
     
    </body>
    </html>
    
    d
    d
    d
    d
    d

    上篇:height()

    下篇:outerHeight()