我正在开发一个标签滚动器,如果标签数量多于当前包含的 div,它基本上允许用户向左或向右滚动标签 block 。我的计划是将组件 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>
最佳答案
我使用了 jQuery externalWidth 方法。
$(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>
关于javascript - 溢出内容的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34599875/