2011-03-27 5 views
2

마우스 포인터를 가져 가면 JavaScript로 단어를 강조 표시 (css : background-color)하려면 어떻게합니까? 그것을 클릭하고 변수에 저장하여 선택할 수 있어야합니다.JavaScript : 마우스 포인터 아래에 단어 강조 표시/선택

+0

[마우스 포인터 아래의 텍스트를 얻기]의 중복 가능성 (http://stackoverflow.com/questions/2183335/getting-the-text-under-the -mouse-pointer) –

답변

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

+0

흠 .. .. 더 느린 속도 일 수 있습니다 .. 더 빠른 방법이 있는지 모르겠다. –

+0

호버 스타일은 CSS로 할 수 있으며, 'delegate'는 이벤트가 치기 전에 지나야하는 요소의 수를 줄인다. 핸들러. 그렇지 않으면 아마도 효율적으로 할 수있는 다른 방법이 없을 것입니다. –

관련 문제