求助:如何用HTML、CSS、JavaScript实现字母矩阵匹配高亮功能?
实现字母矩阵表格与文本匹配高亮功能
下面是完整的可运行代码,包含矩阵生成、输入监听和高亮匹配的全部逻辑:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>字母矩阵高亮</title> <style> .matrix-table { border-collapse: collapse; margin: 20px 0; } .matrix-table td { width: 30px; height: 30px; border: 1px solid #ddd; text-align: center; font-size: 18px; transition: background-color 0.2s; } .highlight { background-color: #ffeb3b; font-weight: bold; } .input-box { padding: 8px 12px; font-size: 16px; width: 300px; } </style> </head> <body> <input type="text" class="input-box" placeholder="输入要匹配的字母"> <table class="matrix-table" id="matrixTable"></table> <script> // 配置矩阵参数 const ROWS = 5; const COLS = 8; // 生成随机字母矩阵(也可以替换成你需要的固定矩阵) function generateMatrix(rows, cols) { const matrix = []; const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; for (let i = 0; i < rows; i++) { const row = []; for (let j = 0; j < cols; j++) { row.push(letters[Math.floor(Math.random() * letters.length)]); } matrix.push(row); } return matrix; } // 渲染矩阵为表格 function renderMatrix(matrix) { const table = document.getElementById('matrixTable'); table.innerHTML = ''; matrix.forEach(row => { const tr = document.createElement('tr'); row.forEach(letter => { const td = document.createElement('td'); td.textContent = letter; tr.appendChild(td); }); table.appendChild(tr); }); } // 高亮匹配的字母 function highlightMatches(inputText) { const cells = document.querySelectorAll('.matrix-table td'); // 先移除所有高亮 cells.forEach(cell => cell.classList.remove('highlight')); if (!inputText.trim()) return; const target = inputText.toLowerCase(); cells.forEach(cell => { if (cell.textContent.toLowerCase().includes(target)) { cell.classList.add('highlight'); } }); } // 初始化 const matrix = generateMatrix(ROWS, COLS); renderMatrix(matrix); // 监听输入事件 const inputBox = document.querySelector('.input-box'); inputBox.addEventListener('input', (e) => { highlightMatches(e.target.value); }); </script> </body> </html>
关键逻辑说明
- 矩阵生成:默认生成随机大写字母矩阵,你可以修改
generateMatrix函数,替换成自己需要的固定字母数组 - 高亮控制:用CSS类
.highlight定义高亮样式,可根据需求修改背景色、字体样式 - 匹配逻辑:默认不区分大小写,若需要严格区分,删除代码中所有
.toLowerCase()调用即可 - 实时响应:监听输入框的
input事件,用户每输入一个字符就会立刻更新高亮状态
内容的提问来源于stack exchange,提问作者Fee
相关产品推荐
相关产品推荐

