我正在创建一个简单的texteditor,为此我正在使用一个函数来获取textarea的选定文本。
我的问题是没有获取所选文本,但是当我向所选文本添加一些标签时,例如粗体或斜体,它会附加。所以我想要的是在将选择添加到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);
};
提前感谢!
答案 0 :(得分:2)
我认为这适合你:
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);
};