如何用 jQuery 的 .width() 测量和设置内容宽度

jQuery 的 .width() 会以数值形式读取首个匹配元素的内容宽度,也可以给所有匹配元素设置内容宽度。读取的单位是像素,范围不包含内边距、边框和外边距。需要测到盒子的其他边界时,可以用 .innerWidth() 或 .outerWidth()。

读取或设置内容宽度

jQuery .width() 官方文档说明读取结果是数值。即使样式表用百分比设定宽度,返回的也是浏览器计算出的内容宽度,可能包含小数。

要以字符串形式读取 CSS 宽度属性,可用 jQuery .css()。采用 box-sizing: border-box 时,CSS 的 width 包含内边距和边框,而 .width() 测量的是内容区。

const $box = $("#box");
const width = $box.width();

$box.width(300);
$box.width("50%");

传入 300 这类数值时,单位是像素。使用其他单位时传入 "50%" 这样的字符串。要让宽度持续随容器调整,可以在 CSS 中设置百分比和限制。

比较内边距、边框和外边距的测量值

jQuery .innerWidth() 测到内边距,jQuery .outerWidth() 测到边框。.outerWidth(true) 还会加上左右外边距。表中是下面的示例在应用最大宽度之前的结果。

调用 测量范围 初始结果 将内容宽度设为 300 后
.width() 内容盒 250 300
.innerWidth() 内容和内边距 290 340
.outerWidth() 内容、内边距和边框 300 350
.outerWidth(true) 边框盒和外边距 320 370
.css("width") 计算后的 CSS 宽度字符串 300px 350px

初始边框盒宽度为 300px。减去 40px 的水平内边距和 10px 的边框,内容宽度为 250px。测量外边距时,左右各加 10px。

在浏览器中设置宽度和上限

把代码保存为 UTF-8 编码的 example.html,再用浏览器打开。示例从外部加载 jQuery 4.1.0,需要联网。在窄屏上,示例盒子可以在自己的区域内横向滚动。

<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>用 jQuery .width() 测量盒子宽度</title>
  <style>
    body { max-width: 32rem; margin: 1rem auto; padding: 0 1rem; font: 1rem/1.5 system-ui; }
    .viewport { overflow-x: auto; }
    #box { box-sizing: border-box; width: 300px; padding: 20px; border: 5px solid #835b00; margin: 10px; }
    button { font: inherit; max-width: 100%; }
    #output { white-space: pre-wrap; overflow-wrap: anywhere; }
  </style>
  <script src="https://code.jquery.com/jquery-4.1.0.min.js"></script>
</head>
<body>
  <div class="viewport"><div id="box">要测量的盒子</div></div>
  <button id="resize" type="button">将内容宽度设为 300px</button>
  <button id="limit" type="button">将最大宽度限制为 320px</button>
  <p>当前测量结果</p>
  <pre id="output" aria-live="polite"></pre>
  <script>
    $(function () {
      const $box = $("#box");

      function report() {
        const widths = {
          ".width()": $box.width(),
          ".innerWidth()": $box.innerWidth(),
          ".outerWidth()": $box.outerWidth(),
          ".outerWidth(true)": $box.outerWidth(true),
          '.css("width")': $box.css("width")
        };
        $("#output").text(JSON.stringify(widths, null, 2));
      }

      $("#resize").on("click", function () {
        $box.css("max-width", "").width(300);
        report();
      });
      $("#limit").on("click", function () {
        $box.css("max-width", "320px");
        report();
      });
      report();
    });
  </script>
</body>
</html>

点击“将内容宽度设为 300px”后,.width() 返回 300,.innerWidth() 返回 340,.outerWidth() 返回 350。内边距和边框给内容宽度增加了 50px,所以 CSS 宽度为 350px。

再点击“将最大宽度限制为 320px”。在 border-box 下,边框盒被限制在 320px,内容剩下 270px。加上外边距为 340px。若要知道实际尺寸,请在设置后重新测量。

检查测量目标和条件

如果结果出乎预期,请先检查匹配了哪些元素。元素或其父元素被隐藏时,结果可能不可靠。尽量测量可见元素,同时考虑浏览器缩放和小数像素。

$(window).width() 返回视口宽度,$(document).width() 返回文档宽度。根据任务选择元素的内容盒、可见区域或整个文档。