2010-08-02 44 views
0

当用户将鼠标悬停在某些文本/关键字上时,如何显示工具提示?这个文本体直接从数据库中检索出来,所以我无法将任何span或div标签或标题信息添加到这些关键字中。有没有办法自动为页面中包含的某些单词创建工具提示?添加没有span标签或标题的工具提示/气泡显示

请让我知道是否有任何关于如何解决这个问题的好教程。

+1

即使文本是从数据库中读取,你仍然应该能够呼应它 – 2010-08-02 15:18:41

回答

3
// Create tooltips dictionary 
$tooltips = Array("Word1"=>"This word is word number 1", 
        "Word2"=>"This word is word number 2"); 

$content = "Here are Word1 and Word2"; 
foreach ($tooltips as $word=>$tip){ 
    $content = preg_replace("/(".$word.")/", "<span title='".$tip."'>$1</span>", $content); 
} 
echo $content; 
+0

注意,“字1”和“字2”是不能包含“/” – opatut 2010-08-02 15:33:14

+0

感谢正则表达式之前包裹在一个跨度的关键字帮助。这个解决方案适用于我。这也是我找到的最有效的解决方案。 – m0g 2010-08-02 17:37:00

2

我不得不这样做是前一阵子。其实我在这里回答了一个类似的问题:javascript: find strings in dom and emphasize it(花了我一段时间来寻找它)。

下面是我用做动态提示一点:

// keyword : tooltip 
keywords = { 
    'hello world' : 'a common first example program', 
    'goodbye cruel world' : 'the opposite of hello world' 
}; 
function insertTooltips (domNode) { 
    if (domNode.nodeType === Node.ELEMENT_NODE) { // We only want to scan html elements 
     var children = domNode.childNodes; 
     for (var i=0;i<children.length;i++) { 
      var child = children[i]; 

      // Filter out unwanted nodes to speed up processing. 
      // For example, you can ignore 'SCRIPT' nodes etc. 
      if (
       child.nodeName != 'span' || 
       child.className != 'tooltip_span' 
      ) { 
       insertTooltips(child); // Recurse! 
      } 
     } 
    } 
    else if (domNode.nodeType === Node.TEXT_NODE) { // Process text nodes 
     var text = domNode.nodeValue; 

     // This is another place where it might be prudent to add filters 

     for (var i in keywords) { 
      if (keywords.hasOwnProperty(i)) { 
      var match = text.indexOf(i); // you may use search instead 
      if (match != -1) { 
       // This is how you wrap the keyword in a span: 

       // create a span: 
       var span = document.createElement('SPAN'); 

       // split text into 3 parts: before, mid and after 
       var mid = domNode.splitText(match); 
       mid.splitText(i.length); 

       // then assign mid part to span 
       mid.parentNode.insertBefore(span,mid); 
       mid.parentNode.removeChild(mid); 
       span.appendChild(mid); 

       // now we can assign a mouseover event handler to the span 
       span.onmouseover = function(){ 
        showToolTip(keywords[i]); 
       } 

       // give the span a class name to prevent accidental 
       // recursion into it: 
       span.className = 'tooltip_span'; 
      } 
      } 
     } 
    } 
} 

的showTooltip功能的实现就留给读者自己练习。

这个想法基本上是使用DOM操作来动态搜索和包装跨度中的关键字,然后为跨度指定鼠标悬停(或鼠标点击,由您决定)处理程序以显示工具提示。在我的网站上,关键字/工具提示哈希/对象是从数据库中抽出的数据生成的。

这比使用正则表达式试图做到这一点要可靠得多,因为它可以防止意外处理与类名,id和脚本标记中的关键字匹配的单词。