簡體   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