Highlight selected text with jquery

烈酒焚心 提交于 2019-12-19 21:59:50

问题


When a user selects any text in my html page I want to add a custom style (like color:red;) to it. This will act as a highlighting tool similar to what you can see in some applications for reading pdf files.

To do this I declare highlight() function that gets the text which is selected, plus its position.

function highlight(text, x, y) {
        alert(text+'***'+x+'***'+y)
        window.getSelection().removeAllRanges();
    }

jsfiddle link edited

jsFiddle


回答1:


Try this approach instead. Basic steps are get your selection, pass it into the getRangeAt method and then create a new span element to surround the selection and apply your class attribute.

$(document).on("mouseup", function (e) {
    var selected = getSelection();
    var range = selected.getRangeAt(0);
    if(selected.toString().length > 1){
        var newNode = document.createElement("span");
        newNode.setAttribute("class", "red");
        range.surroundContents(newNode);       
    }
    selected.removeAllRanges();
 });

function getSelection() {
    var seltxt = '';
     if (window.getSelection) { 
         seltxt = window.getSelection(); 
     } else if (document.getSelection) { 
         seltxt = document.getSelection(); 
     } else if (document.selection) { 
         seltxt = document.selection.createRange().text; 
     }
    else return;
    return seltxt;
}

DEMO




回答2:


After some research i suggest to go this way.

html

<h3 class="foo">hello world! hello world! hello world</h3>
<div class="foo">hello world! hello world hello world!</div>
<span class="foo">hello world! hello world</span>

css

.foo::selection {
    color:#ff0099;
}

.bar::selection {
    color: red;   
}

js

$(document).ready(function(){
    $(".foo").removeClass("foo").addClass("bar");
});

fiddle

First add a class in your element you want to use the effect. After use selection selector and with js add and remove the classes. Hope that helps :)



来源:https://stackoverflow.com/questions/24342007/highlight-selected-text-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!