在 JSP 頁面實現:當使用者點擊(focus)某個文字輸入框時,在其右側顯示「刪除」按鈕;點擊其他輸入框或空白處失去焦點時,該按鈕自動消失。
<input> 綁定 focus 與 blur 事件。$('.input-with-clear').on('focus', function() {
var $btn = $(this).next('.clear-btn');
if (!$btn.length) {
$btn = $('').insertAfter(this);
$btn.on('click', function(e) {
e.preventDefault();
$(this).prev('input').val('').focus();
$(this).hide();
});
}
$btn.show();
}).on('blur', function() {
var $btn = $(this).next('.clear-btn');
setTimeout(function() { $btn.hide(); }, 150);
});
.clear-btn {
display: none;
position: absolute;
margin-left: -24px; /* 根據輸入框 padding 調整 */
padding: 0 4px;
cursor: pointer;
}
$(document).on('focus', '.input-with-clear', ...)。blur 觸發時機不同,建議搭配 touchend 處理。樓主已自行解決,本文提供通用實作參考供後續開發者參考。