fn_b/public/js/airport-recommendations.js

35 lines
1.7 KiB
JavaScript

document.addEventListener('click', async (event) => {
const button = event.target.closest('[data-airport-coupon]');
if (!button) return;
const status = button.closest('.airport-recommendations').querySelector('.airport-copy-status');
try {
let copied = false;
if (navigator.clipboard?.writeText) {
try { await navigator.clipboard.writeText(button.dataset.airportCoupon); copied = true; } catch { /* Try the user-activated fallback below. */ }
}
if (!copied) {
const field = document.createElement('textarea');
field.value = button.dataset.airportCoupon;
field.setAttribute('readonly', '');
field.style.cssText = 'position:fixed;left:-9999px;top:0';
document.body.append(field);
try { field.select(); copied = document.execCommand('copy'); }
finally { field.remove(); button.focus({preventScroll:true}); }
}
if (!copied) throw new Error('Copy unavailable');
status.textContent = '优惠码已复制';
button.classList.add('is-copied');
button.setAttribute('aria-label', '优惠码已复制');
window.setTimeout(() => {
button.classList.remove('is-copied');
button.setAttribute('aria-label', `复制优惠码 ${button.dataset.airportCoupon}`);
}, 2000);
} catch {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(button.querySelector('span'));
selection.removeAllRanges(); selection.addRange(range);
status.textContent = '已选中优惠码,请长按或使用复制快捷键';
}
});