行動網頁為消除 300ms 點擊延遲,常改用 Zepto 的 tap 事件。但 e.stopPropagation() 在 tap 上不生效,導致「點擊按鈕顯示面板,點擊面板外關閉」的邏輯失效:面板剛顯示即被 document 的 tap 隱藏。
// 失效:stopPropagation 無法攔截 tap 冒泡
$('a.btn').on('tap', function(e) {
e.stopPropagation(); // 無效!
$('div.panel').show();
});
$(document).on('tap', function(e) {
$('div.panel').hide();
});
// 按鈕點擊:直接顯示面板,不阻止冒泡
$('a.btn').on('tap', function() {
$('div.panel').show();
});
// 文件層級:判斷點擊目標是否為按鈕或面板內部
$(document).on('tap', function(e) {
var $target = $(e.target);
// 非按鈕、也非面板內部元素 → 隱藏
if (!$target.hasClass('btn') && $target.closest('div.panel').length === 0) {
$('div.panel').hide();
}
});
tap 是透過 touchstart/touchend 模擬,內部未實作標準冒泡機制,故 stopPropagation 無效。e.target 永遠指向實際觸發觸控的最內層元素,透過 hasClass、closest 即可精準判斷點擊區域。$.fn.clickOutside = function(handler) {
var $el = this;
$(document).on('tap.clickOutside', function(e) {
if (!$el.is(e.target) && $el.has(e.target).length === 0) {
handler.call($el, e);
}
});
return this;
};
// 使用範例
$('div.panel').clickOutside(function() {
$(this).hide();
});
closest 判斷可防止誤關閉。click 與 tap,建議統一改用 pointerdown/pointerup 或 FastClick 統一處理。$(document).off('tap.clickOutside') 避免記憶體洩漏。Zepto tap 事件不支援 stopPropagation 是已知限制,改用 e.target + closest 判斷點擊區域,不僅解決冒泡問題,還能寫出更語意清晰、可維護的互動邏輯。