这是我正在尝试做的事情:
-当窗口的宽度小于700px,用户点击底部的灰色栏,红色菜单会向上滑动并停留在那里。
-当窗口的宽度大于700px时,用户点击灰色条时不会发生任何事情。
我已将 resize() 事件绑定(bind)到浏览器窗口,因此如果用户在页面加载后调整窗口大小,将检测到更改。
这是我的代码笔: http://codepen.io/Chiz/pen/xwrpWG (在您阅读下文之前,请勿点击!)
以下是产生奇怪问题的方法:
1) 在单击上面的 Codepen 链接之前,将窗口大小调整到 700px 以下,然后单击上面我的 codepen(如果不确定 700px 有多宽,请将其设置得非常小)
2) 单击底部的灰色条。红色矩形应该向上滑动并停止。 再次点击。红色矩形向后滑动。反复点击,红色矩形每次上下滑动。这是正确的行为。
3) 现在,无需重新加载或刷新 codepen 即可调整浏览器宽度。 您可以使其变宽或变窄,只要调整窗口大小都无所谓。 再次单击灰色条。错误出现。红色矩形向上向下滑动 MULTIPLE 次!
有时,调整大小的次数越多,滑动的次数就越多! :-O
我该如何解决这个问题?
//bind click event to the gray bar on page's first load
showMenuIfWidthSmallerThanSevenHundred();
//detect window resizes
$(window).resize(function() {
showMenuIfWidthSmallerThanSevenHundred();
});
function showMenuIfWidthSmallerThanSevenHundred() {
if ($(window).innerWidth() <= 700) {
$("div").on("click", function() {
/* make menu fill the entire screen that is
not occupied by the gray bar */
var nMenuHeight = $(window).height() - $(this).height();
$(".menu").height(nMenuHeight);
/* position the menu so that the bottom of the menu
touches the top of the gray bar */
$(".menu").css("bottom", $(this).height());
//make menu slide upwards / downwards
$(".menu").slideToggle();
});
}
}
div {
width: 100%;
height: 53px;
background-color: gray;
position: absolute;
bottom: 0;
}
.menu {
width: 100%;
height: 100px;
background-color: #F08080;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<div class="menu"></div>
最佳答案
您可以进行去抖动以减少触发事件的次数。我推荐 Paul Irish 的 smartresizer,它使用 debouces 来达到这个目的。
http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
正如教程所说,您可以使用这个简单的监听器:
$(window).smartresize(function(){
// code that takes it easy...
});
您可以消除大量触发事件的抖动,例如调整大小、滚动等。
关于jquery - 调整窗口大小时多次调用函数 [JQuery],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33035149/