當用戶將鼠標懸停在某些文本/關鍵字上時,如何顯示工具提示?這個文本體直接從數據庫中檢索出來,所以我無法將任何span或div標籤或標題信息添加到這些關鍵字中。有沒有辦法自動爲頁面中包含的某些單詞創建工具提示?添加沒有span標籤或標題的工具提示/氣泡顯示
請讓我知道是否有任何關於如何解決這個問題的好教程。
當用戶將鼠標懸停在某些文本/關鍵字上時,如何顯示工具提示?這個文本體直接從數據庫中檢索出來,所以我無法將任何span或div標籤或標題信息添加到這些關鍵字中。有沒有辦法自動爲頁面中包含的某些單詞創建工具提示?添加沒有span標籤或標題的工具提示/氣泡顯示
請讓我知道是否有任何關於如何解決這個問題的好教程。
// 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;
其實你可以使用跨度或其他。
您有兩個選擇,第一個是在第一個頁面請求中以「display:none」div或span加載工具提示內容,然後用onmouseover事件顯示它。
第二個選項是執行ajax請求。
你應該在這個看看:http://www.smashingmagazine.com/2007/06/12/tooltips-scripts-ajax-javascript-css-dhtml/
我不得不這樣做是前一陣子。其實我在這裏回答了一個類似的問題: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和腳本標記中的關鍵字匹配的單詞。
即使文本是從數據庫中讀取,你仍然應該能夠呼應它 – 2010-08-02 15:18:41