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

如何获得“overflow-x:auto;”区域内元素的全宽?

  •  0
  • Anna_B  · 技术社区  · 2 年前

    我编码了这个:

    $(document).ready(function() {
      $("button").click(function() {
        alert("Width of #text: " + $("#text").width());
      });
    });
    * {
      margin: 0;
      padding: 0;
      font-family: sans-serif;
    }
    
    #container {
      width: 300px;
      height: 150px;
      background-color: grey;
      position: relative;
    }
    
    #scroll-area {
      overflow-x: auto;
      height: 100%;
    }
    
    #text {
      white-space: nowrap;
    }
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <div id="container">
      <div id="scroll-area">
        <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
      </div>
    </div>
    
    <button>Get width of #text</button>

    我想计算 #text 元素 #container 要素目前,它向我展示 300px 结果。但这是容器的宽度,而不是文本元素的宽度。

    0 回复  |  直到 2 年前
        1
  •  0
  •   Evren    2 年前

    尝试使用 scrollWidth 特色

    $(document).ready(function() {
      $("button").click(function() {
        alert("Width of #text: " + $("#scroll-area")[0].scrollWidth);
      });
    });
    * {
      margin: 0;
      padding: 0;
      font-family: sans-serif;
    }
    
    #container {
      width: 300px;
      height: 150px;
      background-color: grey;
      position: relative;
    }
    
    #scroll-area {
      overflow-x: auto;
      height: 100%;
    }
    
    #text {
      white-space: nowrap;
    }
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <div id="container">
      <div id="scroll-area">
        <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
      </div>
    </div>
    
    <button>Get width of #text</button>