如何在内容可编辑区域上选择替换的文本



我已经实现了将所选文本包装在标签中的功能。您可以尝试单击"应用样式"按钮。
而且我还实现了删除标签的功能。
我想在删除标签时保持文本处于选中状态,但我不知道如何实现它。
我已经在以下代码上尝试过,但它不起作用...
我在Chrome上运行此代码。

http://jsfiddle.net/f5HaK/3/



http://youtube.com/watch?v=VtBSJzoTmys&feature=youtu.be

.HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="js/main.js"></script>
    <link href="css/demo.css" rel="stylesheet" type="text/css">
    <title></title>
</head>
<body>
<div id="buttons">
    <input id="applyStyle" type="button" value="Apply Style" />
    <input id="removeStyle" type="button" value="Remove Style" />    
</div>
<div contenteditable="true">hello world</div>
</body>
</html>

主.js

$(function(){
    var TextManager = function(){
        var sel;
        var naked;
    };
    TextManager.prototype = {
        execCommand: function(commandWithArgs, valueArg){
            var commandArr = commandWithArgs.split(' '),
            command = commandArr.shift(),
            args = commandArr.join(' ') + (valueArg || '');
            document.execCommand(command, 0, args);
        },
        applyStyle: function(tagName, className){
            this.sel = window.getSelection();
            var snipet = '<' + tagName + ' class="' + className + '" >' + this.sel.toString() + '</' + tagName + '>';
            this.execCommand('insertHTML', snipet);
            console.log(this.sel);
            this.sel.extend(this.sel.focusNode, 0);
        },
        removeStyle: function(){
            var jcurnode = $(this.sel.focusNode.parentNode);
            this.naked = jcurnode.text();
            jcurnode.replaceWith(this.naked);
            this.sel.extend(this.sel.focusNode, this.naked.length); //here, I'm trying to select text again which I removed the style.
        },
    };
    textManager = new TextManager();
    $('#applyStyle').on('click', function(){
        textManager.applyStyle('div', 'testclass');
    });
    $('#removeStyle').on('click', function(){
        textManager.removeStyle();
    });
});

演示.css

div {
    outline: none;
    font-size: 20px;
    font-family: 'Meiryo'
}
#buttons{
    margin: 10px;
}
.testclass{
    font-weight: bold;
}

文本不会保持选中状态,因为在调用 jcurnode.replaceWith(this.naked) 时从 DOM 中删除了元素;并且删除的节点不能保持选中状态。您可以通过替换行来修复它

jcurnode.replaceWith(this.naked);

从 删除样式 与以下行:

this.execCommand('removeFormat', "");

您可能希望看到一个列表,其中包含可以使用的所有命令标识符:http://help.dottoro.com/larpvnhw.php

最新更新