[removed] Highlight/select word under mouse pointer

前端 未结 1 1690
慢半拍i
慢半拍i 2021-01-14 06:06

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 s

相关标签:
1条回答
  • 2021-01-14 06:51
    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.net/aD5Mu/

    0 讨论(0)
提交回复
热议问题