这里就是我想要做的事:函数被调用多次时,调整窗口[JQuery的]
- 当窗口宽度小于700像素和用户在底部点击灰色条纹上,一个红色的菜单向上滑动并停留在那里。
- 当窗口宽度大于700px时,用户单击灰色条时不会发生任何事情。
我已经将一个resize()事件绑定到浏览器窗口,以便在页面加载后用户调整窗口大小时检测到更改。
这里是我的codepen: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>
你为什么要绑定_resize_事件处理中_event handler_。因此它被多次调用 – Satpal
如果条件为真,你正在绑定每个调整大小(可以调用100次)的点击事件... –
这意味着我应该把clickMenuIfWidthSmallerThanSevenHundred()函数之外的click事件部分?也许把它放在document.ready()函数中? TKS! – Xeon