将高亮显示的文本保存为字符串

Saving highlighted text to a string

本文关键字:保存 字符串 文本 高亮 显示      更新时间:2023-09-26

我正在制作一个web应用程序,将屏幕分成两个窗口,一边是基于web的文本编辑器,另一边只是一个普通的窗口。我正试图找到一种方法,能够让用户在浏览器端突出显示一些文本,然后自动将突出显示的文本保存到字符串中,然后我就能够操纵字符串。

有人有什么想法吗?

        function getSelectionText() {
            var text = "";
            if (window.getSelection) {
                text = window.getSelection().toString();
            } else if (document.selection && document.selection.type != "Control") {
                text = document.selection.createRange().text;
            }
            return text;
        }
        $(document).ready(function (){
           $('div').mouseup(function (e){
               alert(getSelectionText())
           })
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
        Hello, this is a highlight text test
    </div>

这里有两个步骤。

  1. 捕捉mouseup事件
  2. 返回选中的文本。

在文档中选择的任何文本都可以通过js调用访问:

window.getSelection()

但是这是浏览器特有的。因此,您可以使用此代码片段来涵盖从所有浏览器抓取选定文本。

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

我假设您正在使用jQuery之类的库。这可以帮助处理mouseup事件。您可能不希望捕获整个文档上的选择。所以你可以绑定到任何你需要的元素。比如这里的jsfiddle: http://jsfiddle.net/xh799/