我的网站上有一个导航栏,该导航栏太宽,无法在移动设备上显示所有按钮。所以我想在导航按钮距视口(viewport)的偏移小于 150px 时隐藏(下拉菜单将取代它)。如果偏移量超过150px,则需要显示导航栏。
我做了一个Fiddle这显示了我想要的(调整窗口大小)。它正确地从 View 中隐藏了导航栏,但如果偏移量大于 150,则不会使其再次出现。
我知道发生这种情况是因为元素的宽度为“auto”,因此无法检查条件,但我不知道解决方法。
如何解决这个问题?谢谢。
HTML
<div>
<div class="container">
<div class="item">Some</div>
<div class="item">Example</div>
<div class="item">Text</div>
</div>
</div>
CSS
div {
background: red;
text-align: center;
}
.container {
display: inline-block;
background: green;
}
.item {
display: inline-block;
background: green;
}
JS
$(window).on('resize', function(){
var offset = $('.container').offset();
if (offset.left < 150) {
$('.container').hide();
} else {
$('.container').show();
}
}).resize();
最佳答案
发生这种情况的原因是,一旦隐藏某些内容,它就不再渲染,因此它不知道容器的 .offset() 。
也许可以尝试使用 css“可见性”?
参见:http://jsfiddle.net/hnwacrzq/5/
$(window).on('resize', function(){
var offset = $('.container').offset();
console.log(offset);
if (offset.left < 150) {
$('.container').css("visibility", "hidden");
} else {
$('.container').css("visibility", "visible");
}
}).resize();
关于javascript - jQuery 隐藏/显示偏移问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32771418/