在行動版或側邊選單中,常需要點擊選單以外的區域就自動關閉。關鍵在於事件傳遞:選單按鈕的點擊事件要停止冒泡,避免被頁面全域點擊事件立刻關閉。

$(document).click(function () {
$("#sider").animate({ left: -120 }, 1000, function () {
$("#more").addClass("moreno");
});
});
$("#more").click(function (event) {
event.stopPropagation();
if ($("#more").hasClass("moreno")) {
$("#sider").animate({ left: 0 }, 1000, function () {
$("#more").removeClass("moreno");
});
} else {
$("#sider").animate({ left: -120 }, 1000, function () {
$("#more").addClass("moreno");
});
}
});

若不加上 stopPropagation(),按鈕點擊會冒泡到 document,導致選單才打開就被關閉。