如何以编程方式从字符串值中选择文本?

时间:2018-02-07 21:28:04

标签: javascript jquery

我无法使用javascript恢复所选文字 当用户使用鼠标从页面A中选择一些文本时。该选择保存在localStorage中。

我能够存储选定的字符串。我打算使用

恢复选择
$(window).on("load", function () {
    restoreSelection();
});

但是,我无法恢复该字符串。这是我的代码。任何帮助,将不胜感激。



    $(".main").mouseup(function () {


        var range, sel;
        var colour = 'yellow';

        if (window.getSelection) {
            // IE9 and non-IE
            try {
                if (!document.execCommand("BackColor", false, colour)) {
                    makeEditableAndHighlight();
                }
            } catch (ex) {
                makeEditableAndHighlight()
            }

        }
    });
    
    
function makeEditableAndHighlight() {
    var colour = 'yellow';
    var range, sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";

    saveSelections(sel);
}


function saveSelections(selection) {

    if(selection){
        var highlight = selection.toString();
        // localStorage.setItem('textSelection', highlight);


    }

}


function restoreSelection() {
//var highlight = localStorage.getItem('textSelection');

    
if (highlight) {
 
     //I am stumped here I have tried 
       //CreateRange() but nothing works
    }

}

div.storyText * ::selection {
    background: #FFFF00; /* WebKit/Blink Browsers */
  }
  div.storyText * ::-moz-selection {
    background: #FFFF00; /* Gecko Browsers */
  }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main ">

<p>Blalalalalalalalalalalalalala lorem ipsum text textstsetew </p>
</div>
&#13;
&#13;
&#13;

有谁有任何想法?感谢

0 个答案:

没有答案