JavaScript:在鼠标指针下突出显示/选择单词 [英] JavaScript: Highlight/select word under mouse pointer

查看:115
本文介绍了JavaScript:在鼠标指针下突出显示/选择单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当鼠标指针悬停在单词上时,如何使用JavaScript突出显示(css:background-color)单词?应该可以通过点击然后将其保存在变量中来选择它。

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.

推荐答案

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/

这篇关于JavaScript:在鼠标指针下突出显示/选择单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆