2011-03-27 75 views
2

當鼠標指針懸停在JavaScript上時,如何使用JavaScript突出顯示(css:background-color)單詞?應該可以通過點擊選擇它並將其保存在一個變量中。JavaScript:突出顯示/選擇鼠標指針下的單詞

+0

[獲取鼠標指針下的文本]的可能重複(http://stackoverflow.com/questions/2183335/getting-the-text-under-the -mouse-pointer) – 2011-03-27 11:15:29

回答

4
var words=$("#yourTextContainer").text().split(' '); 
$("#yourTextContainer").html(""); 
$.each(words, function(i,val){ 
//wrap each word in a span tag 
$('<span/>').text(val+" ").appendTo("#yourTextContainer"); 

}); 
$("#yourTextContainer span").live("mouseover",function(){ 
//highlight a word when hovered 
$(this).css("background-color","yellow"); 
}); 
$("#yourTextContainer span").live("mouseout",function(){ 
//change bg to white if not selected 
if($(this).css("background-color") !="rgb(0, 0, 255)") 
{ 
$(this).css("background-color","white"); 
} 
}); 
$("#yourTextContainer span").live("click",function(){ 
$("#yourTextContainer span").css("background-color","white"); 
$(this).css("background-color","blue"); 
//gets the text of clicked span tag 
var text = $(this).text(); 
}); 

編輯:參見示例http://jsfiddle.net/aD5Mu/

+0

這是一個很好的答案,但請記住,這可能會很慢,大量的文本。 – tobint 2011-03-27 11:11:21

+0

嗯..可能會慢..不知道是否有更好的更快的方法.. – 2011-03-27 11:15:39

+0

懸停樣式可以用CSS來完成,'委託'會減少事件在擊中之前必須經過的元素數量處理程序。否則,可能沒有其他方法可以高效地完成這個 – 2011-03-27 11:17:08

相關問題