代码之家  ›  专栏  ›  技术社区  ›  ygoe

确定flexbox的所需宽度[重复]

  •  2
  • ygoe  · 技术社区  · 7 年前

    我的页面底部有一个按钮面板。容器是一个flexbox,所有按钮在一行中对齐,没有包装。按钮是 <button> <a> 具有图标和文本作为其内容的元素。现在,由于页面太窄,无法包含所有按钮,我想将按钮缩小到可用空间。只有最右边的按钮会收缩。当其宽度下降到某个阈值以下时,按钮将仅折叠为图标。然后,右边的“下一步”按钮将缩小。

    这种方法在表中运行良好。表总是与其内容一样宽,即使其父表没有其内容那么宽。但flexbox似乎永远不会这样做。

    如何使用JavaScript或jQuery代码找出flexbox所需的宽度?这是适合所有flexbox内容所需的宽度。

    “所需宽度”这个名称来自Windows窗体或WPF,但它似乎没有在HTML中使用。所以如果我需要更好的搜索词,请让我知道。

    这里有一个例子。宽度 .container 限制为200px;在我的例子中,它被限制为页面宽度减去填充。

    * {
      box-sizing: border-box;
    }
    
    .container {
      width: 200px; 
      background: azure;
      padding: 10px;
    }
    
    .buttons {
      background: bisque;
      padding: 10px;
      display: flex;
      white-space: nowrap;
    }
    
    .buttons button,
    .buttons a {
      flex-shrink: 0;
    }
    <div class="container">
      <div class="buttons">
        <button>Button 1</button>
        <button>Button 2</button>
        <button>Button 3</button>
        <button>Button 4</button>
      </div>
    </div>
    1 回复  |  直到 7 年前
        1
  •  0
  •   ygoe    7 年前

    经过大量的尝试和发现 a similar question 碰巧,这段代码似乎满足了我的需要:

    // Returns the total width of all children including their margins.
    function childrenWidth(parent) {
        let contentWidth = 0;
        parent.children().each(function () {
            contentWidth += $(this).outerWidth(true);
        });
        return contentWidth;
    }
    
    let contentWidth = childrenWidth(flexBox);
    

    但这可能也足够了,它返回一个四舍五入的值:

    // flexBox is a jQuery object
    let contentWidth = flexBox[0].scrollWidth;
    

    也可以不使用jQuery。