用jQuery突出显示所选文本 [英] Highlight selected text with jquery

查看:83
本文介绍了用jQuery突出显示所选文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在我的html页面中选择任何文本时,我想为其添加自定义样式(如color:red;).这将用作突出显示工具,类似于您在某些阅读pdf文件的应用程序中看到的工具.

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.

为此,我声明了highlight()函数,该函数获取选定的文本以及其位置.

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链接已编辑

jsfiddle link edited

jsFiddle

推荐答案

请改用此方法.基本步骤是获取选择,将其传递到getRangeAt方法中,然后创建一个新的span元素以包围选择并应用您的class属性.

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;
}

这篇关于用jQuery突出显示所选文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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