[英]How to delete a selection of textarea
I'm making aa simple texteditor and for that I'm using a function which gets the selected text of a textarea. 我正在做一个简单的texteditor,为此,我正在使用一个函数,该函数获取textarea的选定文本。
My problem is not getting the selected text but when i add some tags to the selected text, for example bold or italic, it appends. 我的问题不是获取所选文本,而是当我向所选文本中添加一些标签(例如,粗体或斜体)时,它会追加。 So what I want is to delete the selection first before adding it to the textarea.
所以我想要的是先删除选择,然后再将其添加到文本区域。
Here's my code: 这是我的代码:
<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);
};
thanks in advance! 提前致谢!
I think this works for you: 我认为这对您有用:
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/ https://jsfiddle.net/3L659v65/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.