如何删除选定的文本区域

How to delete a selection of textarea

我正在制作一个简单的文本编辑器,为此我使用了一个函数来获取文本区域的选定文本。

我的问题不是获取所选文本,而是当我向所选文本添加一些标签(例如粗体或斜体)时,它会附加。所以我想要的是先删除选择,然后再将其添加到文本区域。

这是我的代码:

<input type="button" id="bold" value="BOLD"/>
<input type="button" id="undo" value="UNDO"/>
<textarea id="message" cols="50" rows="20"></textarea>

var text = [];
var textarea = document.getElementById('message');
//simple texteditor
function edit(tag) {
    var startPos = textarea.selectionStart;
    var endPos = textarea.selectionEnd;
    var selection = textarea.value.substring(startPos, endPos);
    var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">");
    textarea.value += surrounder;
    updatePreview();
    textarea.focus();
}
document.getElementById('bold').onclick = function () {
    edit('b');
};
document.getElementById('undo').onclick = function () {
    document.execCommand('undo',false,null);
};

提前致谢!

我认为这对你有用:

var text = [];
var textarea = document.getElementById('message');
//simple texteditor
function edit(tag) {
    var startPos = textarea.selectionStart;
    var endPos = textarea.selectionEnd;
    console.log(startPos);
    var selectionBefore = textarea.value.substring(0, startPos);
    var selection = textarea.value.substring(startPos, endPos);
    var selectionAfter = textarea.value.substring(endPos);
    var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">");
    var newText = selectionBefore + surrounder + selectionAfter;
    textarea.value = newText;
    updatePreview();
    textarea.focus();
}
document.getElementById('bold').onclick = function () {
    edit('b');
};
document.getElementById('undo').onclick = function () {
    document.execCommand('undo',false,null);
};

https://jsfiddle.net/3L659v65/