简体   繁体   English

悬停时如何向网页上的单词添加弹出(工具提示)定义?

[英]How can I add pop-up (tooltip) definitions to words on a webpage when hovered?

My 250 page website has a glossary with many words and their definitions.我的 250 页网站有一个词汇表,其中包含许多单词及其定义。 I would like to find a way to have the words in the glossary highlighted whenever they appear in the website text, and present a "tooltip" bubble showing the word's definition when hovered.我想找到一种方法,让词汇表中的单词在网站文本中出现时突出显示,并在悬停时显示一个“工具提示”气泡,显示单词的定义。 My website pages are all html -- I am not using a CMS.我的网站页面都是 html——我没有使用 CMS。

I imagine I will need to use javascript for this.我想我需要为此使用 javascript。 I have looked and looked and have found javascript functions that can highlight certain text (ie wrap it in a span tag), but I do not know how to get this to iterate through an array of the words and include their definitions, and I'm not sure how resource-intensive this would be.我看了又看,发现了 javascript 个函数可以突出显示某些文本(即将它包装在 span 标签中),但我不知道如何让它遍历单词数组并包含它们的定义,我'我不确定这会占用多少资源。

Is there a glossary type program in existence that would work for me without having to manually update every instance of each word throughout the entire website?是否存在一个词汇表类型的程序可以为我工作,而无需手动更新整个网站中每个单词的每个实例? Or is there a fairly straightforward way to achieve this?还是有一种相当直接的方法来实现这一目标? Thanks!谢谢!

This can be done using JQuery and having the glossary be a hidden div on the page, which can be loaded using AJAX if you want.这可以使用 JQuery 并将词汇表作为页面上的隐藏 div 来完成,如果需要,可以使用 AJAX 加载它。

 $("#glossary h2").each(function(index) { // Get the word and its definition. var word = $(this).text(); var def = $("#glossary").find("p")[index].innerHTML; // Update all instances of that word in the content page with mouse over def. var contentHTML = $("#content").html(); contentHTML = contentHTML.replace(new RegExp(word, 'g'), '<span title="' + def + '">' + word + '</span>'); $("#content").html(contentHTML); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="content"> Will likes to hang out with Jim. </div> <div id="glossary" style="display:none;"> <h2>Will</h2> <p>This is will's def.</p> <h2>Jim</h2> <p>This is jim's def.</p> </div>

The above function assumes that you have a single <p> for every <h2> and that all contents of the <p> are part of the definition.上面的 function 假设每个<h2>都有一个<p>并且<p>的所有内容都是定义的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM