javascript - 如何删除选定的文本区域

标签 javascript 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/

关于javascript - 如何删除选定的文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28761239/

相关文章:

javascript - 如何创建一个在其值中带有引号的字符串变量?

html - 文本区域中的字体一致性

javascript - Textarea 空检查

javascript - Rails 中提交的表单数据错误

javascript - 我们可以在一个 slim 的组件中编写 typescript 吗?

javascript - 迭代数组

javascript - jQuery 交替点击执行某些操作

jquery - 使用 jQuery 更改文本区域文本

html - 无法减小 Chrome 和 Opera 中文本区域的大小

html - 在 Bootstrap 模式中将文本区域宽度设置为 100%