2011-03-27 38 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