当前位置:首页 > 行业动态 > 正文

按字母拼音检索汉字js特效

基于键值对存储汉字与拼音映射关系,监听输入框键入事件,实时过滤匹配拼音首字母的 汉字集合,动态渲染

数据准备与结构设计

汉字拼音数据结构

需构建汉字与拼音首字母的映射关系,通常以数组形式存储:

const hanziList = [
  { hanzi: '啊', py: 'A' },
  { hanzi: '阿', py: 'A' },
  { hanzi: '唉', py: 'A' },
  { hanzi: '挨', py: 'A' },
  // 其他汉字...
];
字段名 类型 说明
hanzi String 汉字字符
py String 拼音首字母(大写)

拼音归一化处理

需将用户输入统一转为大写,并与 py 字段匹配:

const inputPy = userInput.toUpperCase();

核心功能实现

动态检索逻辑

通过 Array.filter 筛选匹配项:

function searchByPy(input) {
  const filtered = hanziList.filter(item => item.py === input.toUpperCase());
  return filtered;
}

实时渲染列表

监听输入框事件并更新 DOM:

const inputBox = document.getElementById('py-input');
const resultBox = document.getElementById('result-list');
inputBox.addEventListener('input', () => {
  const results = searchByPy(inputBox.value);
  resultBox.innerHTML = results.map(item => `<li>${item.hanzi}</li>`).join('');
});

视觉特效增强

列表渐显动画

使用 CSS 过渡控制列表出现/隐藏:

#result-list {
  opacity: 0;
  transition: opacity 0.3s;
}
#result-list.show {
  opacity: 1;
}
inputBox.addEventListener('input', () => {
  const results = searchByPy(inputBox.value);
  resultBox.innerHTML = results.map(item => `<li>${item.hanzi}</li>`).join('');
  results.length > 0 ? resultBox.classList.add('show') : resultBox.classList.remove('show');
});

鼠标悬停高亮

#result-list li:hover {
  background-color: #e0f7fa;
  color: #00695c;
  transform: scale(1.05);
  transition: all 0.2s;
}

完整代码示例

<input type="text" id="py-input" placeholder="输入拼音首字母" maxlength="1">
<ul id="result-list"></ul>
const hanziList = [
  { hanzi: '啊', py: 'A' },
  { hanzi: '白', py: 'B' },
  { hanzi: '才', py: 'C' },
  // 更多数据...
];
document.getElementById('py-input').addEventListener('input', function() {
  const input = this.value.toUpperCase();
  const results = hanziList.filter(item => item.py === input);
  const listHtml = results.map(item => `<li>${item.hanzi}</li>`).join('');
  const resultBox = document.getElementById('result-list');
  resultBox.innerHTML = listHtml;
  resultBox.classList.toggle('show', results.length > 0);
});
#result-list {
  border: 1px solid #ccc;
  padding: 8px;
  max-height: 150px;
  overflow-y: auto;
  opacity: 0;
  transition: opacity 0.3s;
}
#result-list.show {
  opacity: 1;
}
#result-list li {
  padding: 4px 8px;
  cursor: pointer;
}

相关问题与解答

问题1:如何处理多音字(如“行”对应 X/H)?

解答:需扩展数据结构,允许单个汉字对应多个拼音:

const hanziList = [
  { hanzi: '行', py: ['X', 'H'] },
  // 其他汉字...
];

检索时改用 Array.some 判断:

function searchByPy(input) {
  return hanziList.filter(item => 
    item.py.includes(input.toUpperCase())
  );
}

问题2:如何优化大数据量(如数千汉字)的检索性能?

解答:可预构建按拼音分类的 Map 结构:

const pyMap = new Map();
hanziList.forEach(item => {
  if (!pyMap.has(item.py)) {
    pyMap.set(item.py, []);
  }
  pyMap.get(item.py).push(item.hanzi);
});

检索时直接取 Map 值:

function searchByPy(input) {
  return pyMap.get(input.toUpperCase()) || [];
}
0