【问题标题】:Width of overflowed content溢出内容的宽度
【发布时间】:2016-01-05 06:03:22
【问题描述】:

我正在开发一个标签滚动器,如果标签多于当前包含的 div,它基本上允许用户向左或向右滚动标签块。我的计划是将组件 div 设置为溢出:隐藏,这样标签(及其父 div)就不会换行。然后我会有左右箭头,可以让标签包装器向左或向右移动。

我需要确定标签包装器的宽度是否大于标签滚动器本身。如果是这样,那么我知道标签滚动器中的标签数量过多,我应该使箭头可见,以便用户可以单击滚动并查看更多内容。布局和一切看起来都符合预期,但我的问题是,使用 $('.tag-wrapper').width();总是根据窗口宽度返回不同的值,因为实际内容没有改变,所以不应该是这种情况。如果屏幕足够宽,我可能不需要显示箭头,所以我需要检查窗口调整大小等的宽度。

任何想法为什么 $('.tag-wrapper').width();即使可滚动内容本身没有改变,也会根据实际窗口宽度给我不同的大小?

这是我的标记:

   .tag-scroller {
     overflow: hidden;
     white-space: no-wrap;
     display: block;
     width: 100%;
     height: 50px;
   }
   .tag-wrapper {
     white-space: nowrap;
     display: inline-block;
     border: 1px solid green;
   }
   .tag {
     display: inline-block;
     width: initial;
     text-align: center;
     padding: 5px 10px 6px 10px;
   }
<div class="tag-scroller">
  <div class="tag-wrapper">
    <div class="tag"></div>
    <div class="tag"></div>
    <div class="tag"></div>
    <div class="tag"></div>
  </div>
</div>

【问题讨论】:

  • 似乎在jsfiddle.net/933oxuz1中按预期工作
  • 使用 jQuery,您可以使用 jQuery 的 width() 属性获取填充的“标签包装器”的总宽度。
  • white-space 属性的正确值为nowrap。除此之外,您的代码似乎工作得很好。预期的结果是什么?

标签: javascript jquery css


【解决方案1】:

我使用了jQuery的outerWidth方法。

$(function() {
  $(document).on('DOMNodeInserted DOMNodeRemoved', '.tag-wrapper', function(e) {
    $('#p').text('tag-wrapper width: ' + $('.tag-wrapper').outerWidth() + 'tag-scroller width: ' + $('.tag-scroller').outerWidth());
    if ($('.tag-wrapper').outerWidth() > $('.tag-scroller').outerWidth()) {
      alert('ok');
    }
  });
  $('#btn').click(function(e) {
    $('.tag-wrapper').append($('<div class="tag">1</div>'));
  });
  $('#btnWidth').click(function(e) {
    $('#p').text('tag-wrapper width: ' + $('.tag-wrapper').outerWidth() + 'tag-scroller width: ' + $('.tag-scroller').outerWidth());
  });
});
.tag-scroller {
  overflow:hidden;
  white-space:no-wrap;
  display:block;
  width:100%;
  height:50px;
}
.tag-wrapper {
  white-space: nowrap;
  display:inline-block;
  border:1px solid green;
}
.tag {
  display:inline-block;
  width:initial;
  text-align:center;
  padding: 5px 10px 6px 10px;
}
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>


<div class="tag-scroller">
    <div class="tag-wrapper">
        <div class="tag">1</div>
        <div class="tag">2</div>
        <div class="tag">3</div>
        <div class="tag">4</div>
    </div>
</div>
<button id="btn">Click Me</button>
<button id="btnWidth">Check Widths</button>
<p id="p"></p>

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多