HTML5+CSS+jQuery 項目,長按圖標 2 秒後在右下角顯示復選框,進入批量選中模式。
var longPressTimer;
var isLongPress = false;
$('.icon').on('touchstart mousedown', function(e) {
var $icon = $(this);
longPressTimer = setTimeout(function() {
isLongPress = true;
$icon.addClass('long-press-active');
// 顯示右下角 checkbox
$icon.find('.batch-checkbox').show();
// 可選:進入全局批量模式
$('body').addClass('batch-mode');
}, 2000); // 2 秒判定長按
}).on('touchend mouseup touchcancel mouseleave', function() {
clearTimeout(longPressTimer);
if (!isLongPress) {
// 短點擊邏輯:跳轉/查看詳情
window.location.href = $(this).data('href');
}
isLongPress = false;
});
// 退出批量模式(如點擊完成按鈕)
$('#btnBatchDone').click(function() {
$('.icon').removeClass('long-press-active');
$('.batch-checkbox').hide().prop('checked', false);
$('body').removeClass('batch-mode');
});
.icon { position: relative; display: inline-block; }
.batch-checkbox {
position: absolute; right: -10px; top: -10px;
display: none; width: 24px; height: 24px;
z-index: 10;
}
.long-press-active { opacity: 0.7; box-shadow: 0 0 10px rgba(0,0,0,0.3); }
touchstart/mousedown 兼容移動端/桌面端touchend/mouseup/touchcancel/mouseleave 完整清理定時器isLongPress 標記區分長按/短按,避免長按後仍觸發短按邏輯batch-mode 類控制整體 UI 狀態(如顯示底部工具欄)若引用 jQuery Mobile,可直接用:
$('.icon').on('taphold', function() {
$(this).addClass('long-press-active').find('.batch-checkbox').show();
});
但 taphold 閾值固定(約 750ms),靈活性不如手動 setTimeout。
長按交互核心:「按下計時 → 達標觸發 → 釋放清理」。手動 setTimeout 完全可控,無框架依賴,適配性最強。