點擊密碼輸入框,彈出虛擬鍵盤(數字隨機排序),用戶點擊按鈕輸入密碼,防止鍵盤記錄器盜取。原文引用外部 JS https://www.yesky.com/imagelist/06/45/13pvu8r78n57.js,現已失效。本文提供**完整自包含實現**。
type="password" + readonly,點擊觸發鍵盤
class VirtualKeyboard {
constructor(inputSelector, options = {}) {
this.input = typeof inputSelector === 'string' ? document.querySelector(inputSelector) : inputSelector;
this.options = {
randomize: true, // 每次打開隨機排序
length: 6, // 密碼長度
onComplete: null, // 輸入完成回調
zIndex: 9999,
...options
};
this.keys = ['0','1','2','3','4','5','6','7','8','9'];
this.value = '';
this.isOpen = false;
this._createKeyboard();
this._bindInput();
}
_createKeyboard() {
this.panel = document.createElement('div');
this.panel.className = 'vk-panel';
this.panel.style.cssText = `
position:fixed; left:0; top:0; width:100%; height:100%;
background:rgba(0,0,0,0.5); z-index:${this.options.zIndex};
display:none; align-items:center; justify-content:center;
`;
this.panel.innerHTML = `
請輸入交易密碼
`;
document.body.appendChild(this.panel);
// 緩存子元素
this.displayEl = this.panel.querySelector('.vk-display');
this.keysEl = this.panel.querySelector('.vk-keys');
this.actionsEl = this.panel.querySelector('.vk-actions');
this.closeBtn = this.panel.querySelector('.vk-close');
// 構建鍵盤
this._renderKeys();
this._renderDisplay();
this._renderActions();
}
_renderKeys() {
const keys = this.options.randomize ? this._shuffle([...this.keys]) : this.keys;
this.keysEl.innerHTML = keys.map(k =>
``
).join('');
// 綁定鍵位點擊
this.keysEl.querySelectorAll('.vk-key').forEach(btn => {
btn.addEventListener('click', () => this._onKey(btn.dataset.key));
btn.addEventListener('mousedown', () => btn.style.background='#e8f0fe');
btn.addEventListener('mouseup', () => btn.style.background='#fafafa');
btn.addEventListener('mouseleave', () => btn.style.background='#fafafa');
});
}
_renderDisplay() {
this.displayEl.innerHTML = '';
for (let i = 0; i < this.options.length; i++) {
const dot = document.createElement('div');
dot.style.cssText = `
width:16px; height:16px; border-radius:50%;
border:2px solid ${i < this.value.length ? '#3498db' : '#ddd'};
background:${i < this.value.length ? '#3498db' : 'transparent'};
transition:all 0.15s;
`;
this.displayEl.appendChild(dot);
}
}
_renderActions() {
this.actionsEl.innerHTML = `
`;
this.actionsEl.querySelector('.vk-backspace').addEventListener('click', () => this._onBackspace());
this.actionsEl.querySelector('.vk-clear').addEventListener('click', () => this._onClear());
this.actionsEl.querySelector('.vk-confirm').addEventListener('click', () => this._onConfirm());
this.confirmBtn = this.actionsEl.querySelector('.vk-confirm');
}
_bindInput() {
this.input.readOnly = true;
this.input.addEventListener('click', () => this.open());
this.input.addEventListener('focus', () => this.open());
// 防止自動填充
this.input.setAttribute('autocomplete', 'off');
this.input.setAttribute('autocapitalize', 'off');
this.input.setAttribute('autocorrect', 'off');
this.input.setAttribute('spellcheck', 'false');
}
_shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
_onKey(key) {
if (this.value.length >= this.options.length) return;
this.value += key;
this._renderDisplay();
this._updateConfirmBtn();
}
_onBackspace() {
this.value = this.value.slice(0, -1);
this._renderDisplay();
this._updateConfirmBtn();
}
_onClear() {
this.value = '';
this._renderDisplay();
this._updateConfirmBtn();
}
_updateConfirmBtn() {
this.confirmBtn.disabled = this.value.length !== this.options.length;
this.confirmBtn.style.opacity = this.confirmBtn.disabled ? '0.5' : '1';
}
_onConfirm() {
if (this.value.length !== this.options.length) return;
this.input.value = this.value;
this.close();
this.options.onComplete?.(this.value);
}
open() {
if (this.isOpen) return;
this.value = '';
this._renderKeys(); // 重新打亂
this._renderDisplay();
this._updateConfirmBtn();
this.panel.style.display = 'flex';
// 焦點陷阱
this._trapFocus();
this.isOpen = true;
}
close() {
this.panel.style.display = 'none';
this.isOpen = false;
}
_trapFocus() {
const focusable = this.panel.querySelectorAll('button');
focusable[0]?.focus();
this.panel.addEventListener('keydown', this._onKeyDown);
}
_onKeyDown = (e) => {
if (e.key === 'Escape') this.close();
if (e.key === 'Tab') {
const focusable = this.panel.querySelectorAll('button');
const first = focusable[0];
const last = focusable[focusable.length - 1];
if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
}
if (/^\d$/.test(e.key)) this._onKey(e.key);
if (e.key === 'Backspace') this._onBackspace();
if (e.key === 'Enter' && !this.confirmBtn.disabled) this._onConfirm();
};
destroy() {
this.panel.remove();
this.input.removeEventListener('click', this.open);
this.input.removeEventListener('focus', this.open);
}
}
// 使用
document.addEventListener('DOMContentLoaded', () => {
const vk = new VirtualKeyboard('#password-input', {
length: 6,
onComplete: (pwd) => console.log('密碼輸入完成:', pwd)
});
});
visibilitychange 模糊面板readonly 阻擋autocomplete="off" autocomplete="new-password"虛擬鍵盤密碼輸入器是銀行級安全組件的經典實現。核心在於:**隨機化鍵位順序、只讀輸入框、純點擊交互、焦點陷阱、無障礙支持**。現代實現應棄用外部腳本依賴,採用 ES6 Class 封裝、CSS Grid/Flex 佈局、原生事件模型、請求動畫幀優化,構建自包含、可配置、可測試的組件。