繁体   English   中英

HTML页面中的文本突出显示

[英]Text highlighting in html page

我正在用jquery在HTML中工作。

我想制作一个网页来一次突出显示该页面中的一些文本行(第15、22、32行)。 可以通过在鼠标上单击鼠标左键并拖动该行来完成,以便选择带有蓝色背景的文本行。

我可以使用jquery如下获得选定的行,

    function getText() {
        var text = "";
        if (window.getSelection) {
            text = window.getSelection().toString();
        } else if (document.selection && document.selection.type != "Control") {
            text = document.selection.createRange().text;
        }
        console.log('text-----------'+text)
    }

当我单击其他行时,第一个选定的行消失了。 我还需要那条线。 (在MSword中,我们可以按住ctrl并拖动线,它将可用)

对于多重选择,我知道网络上有更多可用的插件。 但是我正在寻找使用Javascript或jquery进行选择。

这就是我想要在页面中执行的操作,想要选择文本并在我的javascript函数中获取它们。

在此处输入图片说明

我们该怎么做?

这个答案结合了一些问题。

  1. 获取选择文本
  2. 标记它。
  3. 复制到剪贴板

这不是完整的解决方案,但包含所有部分。

所以:

 var output = ''; $('#test').mouseup(function () { output += getSelectedText(); highlightSelected(); copyOutput(); $('#result').html(output); }); function getSelectedText() { if (window.getSelection) { return window.getSelection().toString(); } else if (document.selection) { return document.selection.createRange().text; } return ''; } function highlightSelected() { var SelRange; if (window.getSelection) { SelRange = window.getSelection().getRangeAt(0); } else if (document.getSelection) { SelRange = document.getSelection().getRangeAt(0); } else if (document.selection) { SelRange = document.selection.createRange(); } if (SelRange.pasteHTML) { SelRange.pasteHTML('<span class="hilited1">' + SelRange.text + '</span>'); } else { var newNode = $('<span class="hilited1" />')[0]; SelRange.surroundContents(newNode); } } function copyOutput() { var emailLink = document.querySelector('#result'); var range = document.createRange(); range.selectNode(emailLink); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); try { var successful = document.execCommand('copy'); } catch (err) { console.log('Oops, unable to copy'); } window.getSelection().removeAllRanges(); } 
 textarea { width:100%; height:150px; } .hilited1 { background:red; color:#fff; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="test">I am working in HTML with jquery. I want to make a webpage to highlight some text lines (line nos 15, 22, 32) in that page at a time. This can be done by left click in mouse and drag that line, so that the text line is selected with blue background. I am able to get the selected lines as follows using jquery, </div> <hr /> <div id="result"></div> <hr /> <textarea placeholder="Try to paste here"></textarea> 

暂无
暂无

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

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