萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS 經典特效:建設銀行風格虛擬鍵盤密碼輸入器

效果描述

點擊密碼輸入框,彈出虛擬鍵盤(數字隨機排序),用戶點擊按鈕輸入密碼,防止鍵盤記錄器盜取。原文引用外部 JS https://www.yesky.com/imagelist/06/45/13pvu8r78n57.js,現已失效。本文提供**完整自包含實現**。

核心設計

  • 輸入框:type="password" + readonly,點擊觸發鍵盤
  • 虛擬鍵盤:浮層彈出,數字 0-9 隨機打亂,含「確定」「清空」「退格」「關閉」
  • 安全性:每次打開重新打亂、輸入不顯示明文、防截屏(可選)、防自動填充
  • 無障礙:鍵盤導航、ARIA 標籤、焦點管理

完整實現(Vanilla JS,無依賴)


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) }); });

HTML



安全性增強建議

  1. 防截屏:移動端可監聽 visibilitychange 模糊面板
  2. 防鍵盤記錄:僅依賴虛擬鍵盤,物理鍵盤輸入被 readonly 阻擋
  3. 防自動填充:autocomplete="off" autocomplete="new-password"
  4. 傳輸加密:前端 RSA 加密密碼再提交,或使用 Web Crypto API
  5. 防暴力破解:後端限制嘗試次數、鎖定賬戶

總結

虛擬鍵盤密碼輸入器是銀行級安全組件的經典實現。核心在於:**隨機化鍵位順序、只讀輸入框、純點擊交互、焦點陷阱、無障礙支持**。現代實現應棄用外部腳本依賴,採用 ES6 Class 封裝、CSS Grid/Flex 佈局、原生事件模型、請求動畫幀優化,構建自包含、可配置、可測試的組件。

copyright © 萬盛學電腦網 all rights reserved