且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript:在鼠标指针下突出显示/选择单词

更新时间:2023-02-01 16:57:40

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/