首页 > 解决方案 > 为什么 div 的测量宽度与浏览器测量不同?

问题描述

我有一个小工具可以尝试几个 flexbox 参数。它可以在 flexbox 容器中添加和删除 div,然后使用 jQuery 显示这些添加元素的宽度。但是测量的宽度与我在浏览器检查器中测量的不同。

使用“加号”和“减号”按钮,可以添加元素。第一个元素的宽度应该是正确的,但后面的元素测量错误。这里发生了什么?

function getWidth() {
  // true: include margins
  var v = parseFloat($(this).outerWidth(true)).toFixed(2);
  var span = '<span>Width: ' + v + '</span>';
  
  console.log(v);
  $(this).html(span);
}

$(document).ready(function() {
  // Initialize.
  var items = 3;
  var itemsDiv = '<div class="item">';
  var HTML = '';
  for (var i = 0; i < items; i++) {
    HTML += itemsDiv + 'Item ' + i + '</div>';
  }
  $('.container').html(HTML)
  var adjustment;

  // Add / remove items
  // Always keep at least one flex item.
  $('input[name="build"]').click(function() {
    adjustment = $(this).val();
    if (adjustment == "plus") {
      items += 1;
    }
    if (adjustment == "minus") {
      if (items > 1) {
        items -= 1;
      }
    }
    HTML = '';
    for (var i = 0; i < items; i++) {
      HTML += itemsDiv + 'Item ' + i + '</div>';
    }
    $('.container').html(HTML);
    $('.item').each(getWidth);
  });

  // Flex direction
  // Select flex-direction radio buttons and get checked value.
  $('input[name="flex-direction"]').click(function() {
    var flexDirection = $('input[name="flex-direction"]:checked').val();
    $('.container').css('flex-direction', flexDirection);
  });

  // Flex wrap
  $('input[name="flex-wrap"]').click(function() {
    var flexWrap = $('input[name="flex-wrap"]:checked').val();
    $('.container').css('flex-wrap', flexWrap);
  })
})
body {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid grey;
  margin: auto;
}

div.item {
  padding: 0;
  /* max-width: 80px; */
  height: 100px;
  margin: auto;
  border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="./flexbox.css">
  <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
  <script src="flexbox.js"></script>
</head>
<body>
  <div class="base">
    <input type="button" name="build" value="plus" id="plus">
    <input type="button" name="build" value="minus" id="minus">
    <div class="container"></div>
    Flex Direction
    <input type="radio" name="flex-direction" id="row" value="row" checked>
    <label for="row">Row</label>
    <input type="radio" name="flex-direction" id="column" value="column">
    <label for="column">Column</label>
    <input type="radio" name="flex-direction" id="row-reverse" value="row-reverse">
    <label for="row-reverse">Row-Reverse</label>
    <input type="radio" name="flex-direction" id="column-reverse" value="column-reverse">
    <label for="column-reverse">Column-Reverse</label>
    <br />
    <input type="radio" name="flex-wrap" id="nowrap" value="nowrap" checked>
    <label for="nowrap">No Wrap</label>
    <input type="radio" name="flex-wrap" id="wrap" value="wrap">
    <label for="wrap">Wrap</label>
    <input type="radio" name="flex-wrap" id="wrap-reverse" value="wrap-reverse">
    <label for="wrap-reverse">Wrap-Reverse</label>
  </div>
</body>
</html>

标签: javascriptjqueryhtmlcssflexbox

解决方案


计算很好,不同之处在于您正在计算第一个的宽度,然后在其中添加会影响另一个的内容。然后你对第二个做同样的事情,等等。

最后,它们在视觉上都将具有相同的outerWidth1,因为它们具有相同的内容,但是在运行 JS 时情况并非如此,您不会注意到这一点。

这是没有向元素添加内容的代码,您可以清楚地看到所有日志都给出相同的结果,这仅仅是因为 HTML在宽度计算期间没有改变。

function getWidth() {
  // true: include margins
  var v = parseFloat($(this).outerWidth(true)).toFixed(2);
  var span = '<span>Width: ' + v + '</span>';
  
  console.log(v);
  //$(this).html(span);
}

$(document).ready(function() {
  // Initialize.
  var items = 3;
  var itemsDiv = '<div class="item">';
  var HTML = '';
  for (var i = 0; i < items; i++) {
    HTML += itemsDiv + 'Item ' + i + '</div>';
  }
  $('.container').html(HTML)
  var adjustment;

  // Add / remove items
  // Always keep at least one flex item.
  $('input[name="build"]').click(function() {
    adjustment = $(this).val();
    if (adjustment == "plus") {
      items += 1;
    }
    if (adjustment == "minus") {
      if (items > 1) {
        items -= 1;
      }
    }
    HTML = '';
    for (var i = 0; i < items; i++) {
      HTML += itemsDiv + 'Item ' + i + '</div>';
    }
    $('.container').html(HTML);
    $('.item').each(getWidth);
  });

  // Flex direction
  // Select flex-direction radio buttons and get checked value.
  $('input[name="flex-direction"]').click(function() {
    var flexDirection = $('input[name="flex-direction"]:checked').val();
    $('.container').css('flex-direction', flexDirection);
  });

  // Flex wrap
  $('input[name="flex-wrap"]').click(function() {
    var flexWrap = $('input[name="flex-wrap"]:checked').val();
    $('.container').css('flex-wrap', flexWrap);
  })
})
body {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid grey;
  margin: auto;
}

div.item {
  padding: 0;
  /* max-width: 80px; */
  height: 100px;
  margin: auto;
  border: 1px solid black;
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="./flexbox.css">
  <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
  <script src="flexbox.js"></script>
</head>
<body>
  <div class="base">
    <input type="button" name="build" value="plus" id="plus">
    <input type="button" name="build" value="minus" id="minus">
    <div class="container"></div>
    Flex Direction
    <input type="radio" name="flex-direction" id="row" value="row" checked>
    <label for="row">Row</label>
    <input type="radio" name="flex-direction" id="column" value="column">
    <label for="column">Column</label>
    <input type="radio" name="flex-direction" id="row-reverse" value="row-reverse">
    <label for="row-reverse">Row-Reverse</label>
    <input type="radio" name="flex-direction" id="column-reverse" value="column-reverse">
    <label for="column-reverse">Column-Reverse</label>
    <br />
    <input type="radio" name="flex-wrap" id="nowrap" value="nowrap" checked>
    <label for="nowrap">No Wrap</label>
    <input type="radio" name="flex-wrap" id="wrap" value="wrap">
    <label for="wrap">Wrap</label>
    <input type="radio" name="flex-wrap" id="wrap-reverse" value="wrap-reverse">
    <label for="wrap-reverse">Wrap-Reverse</label>
  </div>
</body>
</html>

现在,这是在计算其宽度后仅在第一个元素内添加内容时的状态。我们可以清楚地看到,我们没有相同的结构,元素之间的边距也不相同,因此outerWidth第二个元素的边距会不同。

body {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid grey;
  margin: auto;
}

div.item {
  padding: 0;
  /* max-width: 80px; */
  height: 100px;
  margin: auto;
  border: 1px solid black;
}
All the elements have the same outerwidth here
<div class="container">
  <div class="item">Item 0</div>
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>
We add the width calculation inside the first one and the margin will be reduced so the next one will be different
<div class="container">
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item">Item 1</div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>

这是下一个状态,您可以清楚地看到效果。

使用的值是简单的占位符

body {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid grey;
  margin: auto;
}

div.item {
  padding: 0;
  /* max-width: 80px; */
  height: 100px;
  margin: auto;
  border: 1px solid black;
}
<div class="container">
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item">Item 2</div>
  <div class="item">Item 3</div>
</div>
<div class="container">
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item">Item 3</div>
</div>
<div class="container">
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item"><span>Width: 100.66</span></div>
  <div class="item"><span>Width: 100.66</span></div>
</div>


在有 4 个元素的情况下,只有边距受到影响,但是当涉及到更多元素时,内部宽度也可能由于收缩效果而受到影响:

body {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid grey;
  margin: auto;
}

div.item {
  padding: 0;
  /* max-width: 80px; */
  height: 100px;
  margin: auto;
  border: 1px solid black;
}
<div class="container">
  <div class="item">Item 0</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
</div>
<div class="container">
  <div class="item">Width 100</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
  <div class="item">Item 1</div>
</div>


如果你想要一个准确的计算,你应该避免在计算时改变 HTML 内容和 DOM 结构您可以通过添加内容在计算之前和之后更新它,但不能在计算中间进行。


1 :它是包括边距在内的宽度,因为您要添加true到 jQuery 函数。


根据评论,这里是您的原始代码示例,其中span附加了宽度信息,并绝对定位在底部。这样就不会影响计算值。

堆栈片段

function getWidth() {
  // true: include margins
  var v = parseFloat($(this).outerWidth(true)).toFixed(2);
  var span = '<span>Width: ' + v + '</span>';
  
  //console.log(v);
  $(this).append(span);
}

$(document).ready(function() {
  // Initialize.
  var items = 3;
  var itemsDiv = '<div class="item">';
  var HTML = '';
  for (var i = 0; i < items; i++) {
    HTML += itemsDiv + 'Item ' + i + '</div>';
  }
  $('.container').html(HTML)
  var adjustment;

  // Add / remove items
  // Always keep at least one flex item.
  $('input[name="build"]').click(function() {
    adjustment = $(this).val();
    if (adjustment == "plus") {
      items += 1;
    }
    if (adjustment == "minus") {
      if (items > 1) {
        items -= 1;
      }
    }
    HTML = '';
    for (var i = 0; i < items; i++) {
      HTML += itemsDiv + 'Item ' + i + '</div>';
    }
    $('.container').html(HTML);
    $('.item').each(getWidth);
  });

  // Flex direction
  // Select flex-direction radio buttons and get checked value.
  $('input[name="flex-direction"]').click(function() {
    var flexDirection = $('input[name="flex-direction"]:checked').val();
    $('.container').css('flex-direction', flexDirection);
  });

  // Flex wrap
  $('input[name="flex-wrap"]').click(function() {
    var flexWrap = $('input[name="flex-wrap"]:checked').val();
    $('.container').css('flex-wrap', flexWrap);
  })
})
body {
  box-sizing: border-box;
}

.container {
  display: flex;
  flex-direction: row;
  height: 200px;
  width: 400px;
  border: 1px solid grey;
  margin: auto;
}

div.item {
  position: relative;
  padding: 0;
  /* max-width: 80px; */
  height: 100px;
  margin: auto;
  border: 1px solid black;
}

div.item span {
  position: absolute;
  left: 0; bottom: 0;
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="./flexbox.css">
  <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
  <script src="flexbox.js"></script>
</head>
<body>
  <div class="base">
    <input type="button" name="build" value="plus" id="plus">
    <input type="button" name="build" value="minus" id="minus">
    <div class="container"></div>
    Flex Direction
    <input type="radio" name="flex-direction" id="row" value="row" checked>
    <label for="row">Row</label>
    <input type="radio" name="flex-direction" id="column" value="column">
    <label for="column">Column</label>
    <input type="radio" name="flex-direction" id="row-reverse" value="row-reverse">
    <label for="row-reverse">Row-Reverse</label>
    <input type="radio" name="flex-direction" id="column-reverse" value="column-reverse">
    <label for="column-reverse">Column-Reverse</label>
    <br />
    <input type="radio" name="flex-wrap" id="nowrap" value="nowrap" checked>
    <label for="nowrap">No Wrap</label>
    <input type="radio" name="flex-wrap" id="wrap" value="wrap">
    <label for="wrap">Wrap</label>
    <input type="radio" name="flex-wrap" id="wrap-reverse" value="wrap-reverse">
    <label for="wrap-reverse">Wrap-Reverse</label>
  </div>
</body>
</html>


推荐阅读