如何删除选定的文本区域

How to delete a selection of textarea

本文关键字:文本 区域 何删除 删除      更新时间:2024-06-10

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

我的问题不是获取选定的文本,但当我向选定的文本添加一些标记时,例如粗体或斜体,它会附加。所以我想要的是在将所选内容添加到文本区域之前先删除它。

这是我的代码:

<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/