這裏就是我想要做的事:函數被調用多次時,調整窗口[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