admin管理员组

文章数量:1426782

How do I highlight (css: background-color) a word with JavaScript when the mouse pointer is hovering over it? It should be possible to select it by clicking on it then and saving it in a variable.

How do I highlight (css: background-color) a word with JavaScript when the mouse pointer is hovering over it? It should be possible to select it by clicking on it then and saving it in a variable.

Share Improve this question asked Mar 27, 2011 at 10:39 DanDan 311 silver badge2 bronze badges 1
  • possible duplicate of Getting the text under the mouse pointer – Yi Jiang Commented Mar 27, 2011 at 11:15
Add a ment  | 

1 Answer 1

Reset to default 5
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();
});

EDIT:See the example http://jsfiddle/aD5Mu/

本文标签: jqueryJavaScript Highlightselect word under mouse pointerStack Overflow