contenteditable选定的文本保存和恢复 [英] contenteditable selected text save and restore

查看:324
本文介绍了contenteditable选定的文本保存和恢复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这篇文章显示了如何从一个可信的div中保存和恢复所选文本的2个功能。我有下面的div设置为contenteditable和另一个帖子的2功能。如何使用这些功能来保存和恢复所选文本。

I came across this post that shows 2 functions on how to save and restore selected text from a contenteditable div. I have the below div set as contenteditable and the 2 function from the other post. How to i use these functions to save and restore selected text.

<div style="width:300px;padding:10px;" contenteditable="true">test test test test</div>

<script>
function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}
</script>


推荐答案

典型用途是显示某种小部件或用于接受来自用户的输入的对话框(因此可能会破坏原始选择)并在隐藏该窗口小部件后恢复选择。实际上使用这些功能非常简单;最大的危险就是在选择被摧毁后试图保存选择。

A typical use would be displaying some kind of widget or dialog to accept input from the user (thus potentially destroying the original selection) and restoring the selection after that widget has been hidden. Actually using the functions is quite simple; the biggest danger is trying to save the selection after it has already been destroyed.

这是一个简单的例子。它显示文本输入并使用该输入中的文本覆盖可编辑< div> 中的选择。这里有太多的代码要粘贴,所以这里是完整的代码: http://www.jsfiddle.net/timdown/ cCAWC / 3 /

Here's a simple example. It displays a text input and overwrites the selection in the editable <div> with the text from that input. There's too much code to paste in here, so here's the full code: http://www.jsfiddle.net/timdown/cCAWC/3/

摘录:

<div id="test" contenteditable="true">Some editable text</div>
<input type="button" unselectable="on" onclick="displayTextInserter();"
    value="Insert text">
<div id="textInserter">
    <input type="text" id="textToInsert">
    <input type="button" onclick="insertText()" value="Insert">
</div>

<script type="text/javascript">
var selRange;

function displayTextInserter() {
    selRange = saveSelection();
    document.getElementById("textInserter").style.display = "block";
    document.getElementById("textToInsert").focus();
}     

function insertText() {
    var text = document.getElementById("textToInsert").value;
    document.getElementById("textInserter").style.display = "none";
    restoreSelection(selRange);
    document.getElementById("test").focus();
    insertTextAtCursor(text);
}
</script>

这篇关于contenteditable选定的文本保存和恢复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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