实现文本单词悬停查词功能的技术方案咨询
实现悬停单词显示词典释义的方案
以下是基于HTML/CSS/JavaScript的完整实现方案,无需手动录入单词释义,直接对接免费词典API:
1. HTML结构
先搭建基础的文本容器和悬浮释义框:
<div class="text-container"> English teaching programs help students improve their language skills. When encountering unfamiliar words, students need quick access to definitions. </div> <!-- 用于显示释义的悬浮框 --> <div id="word-tooltip" class="tooltip"></div>
2. CSS样式
给悬浮框设置基础样式,确保它在页面上悬浮显示:
.tooltip { position: absolute; background: #ffffff; border: 1px solid #e0e0e0; padding: 8px 12px; border-radius: 4px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); display: none; z-index: 1000; max-width: 280px; font-size: 14px; } .text-container { line-height: 1.8; font-size: 19px; padding: 20px; }
3. JavaScript逻辑
实现鼠标悬停提取单词、调用API获取释义、显示悬浮框的核心功能:
const tooltip = document.getElementById('word-tooltip'); const textContainer = document.querySelector('.text-container'); const wordCache = {}; // 缓存已查询的单词,减少API调用 // 提取鼠标悬停位置的单词 function getHoveredWord(event) { const range = document.caretRangeFromPoint?.(event.clientX, event.clientY); if (!range) return null; // 扩展选中范围到整个单词 range.expand('word'); let word = range.toString().trim(); // 过滤掉单词前后的标点符号 word = word.replace(/^[^a-zA-Z]+|[^a-zA-Z]+$/g, ''); return word.length > 0 ? word.toLowerCase() : null; } // 调用免费词典API获取释义 async function fetchWordDefinition(word) { // 先查缓存,避免重复请求 if (wordCache[word]) return wordCache[word]; try { const res = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`); if (!res.ok) throw new Error('Definition not found'); const data = await res.json(); // 提取第一个有效释义 const definition = data[0].meanings[0].definitions[0].definition; wordCache[word] = definition; // 存入缓存 return definition; } catch (err) { return 'No definition available'; } } // 显示释义悬浮框 function displayTooltip(word, definition, x, y) { tooltip.textContent = `${word}: ${definition}`; tooltip.style.display = 'block'; // 调整位置避免超出屏幕 tooltip.style.left = `${Math.min(x + 15, window.innerWidth - tooltip.offsetWidth - 10)}px`; tooltip.style.top = `${Math.min(y + 15, window.innerHeight - tooltip.offsetHeight - 10)}px`; } // 监听鼠标移动事件 textContainer.addEventListener('mousemove', async (e) => { const word = getHoveredWord(e); if (word) { const definition = await fetchWordDefinition(word); displayTooltip(word, definition, e.clientX, e.clientY); } else { tooltip.style.display = 'none'; } }); // 鼠标离开文本区域时隐藏悬浮框 textContainer.addEventListener('mouseleave', () => { tooltip.style.display = 'none'; });
关键注意事项
- API选择:示例中使用的是免费开源的词典API,支持跨域调用;如果要对接Dictionary.com官方API,需前往其开发者平台注册获取密钥,并调整请求地址和参数,注意遵守调用频率限制。
- 性能优化:通过
wordCache对象缓存已查询的单词,避免重复发起API请求,提升响应速度。 - 单词提取准确性:
caretRangeFromPoint在部分旧浏览器可能存在兼容性问题,可替换为自定义的单词匹配逻辑(比如通过正则遍历文本节点定位鼠标位置的单词)。 - 样式适配:可根据你的教学程序UI风格,修改tooltip的背景色、字体、阴影等样式,确保与整体界面协调。
内容的提问来源于stack exchange,提问作者Axey
相关产品推荐
相关产品推荐

