简体   繁体   English

使用jquery突出显示所选文本

[英]Highlight selected text with jquery

When a user selects any text in my html page I want to add a custom style (like color:red; ) to it. 当用户选择我的html页面中的任何文本时,我想向其添加自定义样式(如color:red; )。 This will act as a highlighting tool similar to what you can see in some applications for reading pdf files. 这将作为一个突出显示工具,类似于您在某些应用程序中看到的用于阅读pdf文件的内容。

To do this I declare highlight() function that gets the text which is selected, plus its position. 为此,我声明了highlight()函数,它获取所选文本及其位置。

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

jsfiddle link edited jsfiddle链接已编辑

jsFiddle 的jsfiddle

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. 基本步骤是获取您的选择,将其传递到getRangeAt方法,然后创建一个新的span元素以包围选择并应用您的类属性。

$(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 DEMO

After some research i suggest to go this way. 经过一些研究后,我建议采取这种方式。

html 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 CSS

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

.bar::selection {
    color: red;   
}

js JS

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

fiddle 小提琴

First add a class in your element you want to use the effect. 首先添加一个class中的元素,你要使用的效果。 After use selection selector and with js add and remove the classes . 使用选择选择器后,用js addremove classes Hope that helps :) 希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM