Общие функции
(function(){
var cache = {};
gid = function(id){
return cache[id] ? cache[id] : cache[id] = document.getElementById(id);
};
})();
function saveSelection() {
var sel = window.getSelection();
return sel.rangeCount ? sel.getRangeAt(0) : null;
}
function restoreSelection(range) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
Сам редактор
addEventListener('load', function() {
var html = gid('htmlContent'), range = null;
html.addEventListener('mouseup', function() {
range = saveSelection();
});
function applyFormat(format, value) {
if (range) {
console.log(range);
restoreSelection(range);
document.execCommand(format, false, value);
console.log(range);
}
}
gid('iconBold').addEventListener('click', function() {
applyFormat('bold');
});
gid('iconItalic').addEventListener('click', function() {
applyFormat('italic');
});
gid('iconUnderline').addEventListener('click', function() {
applyFormat('underline');
});
});
После выполнения document.execCommand изменяется Range
// до:
Range {commonAncestorContainer: text, collapsed: false, endOffset: 16, endContainer: text, startOffset: 13…}
collapsed: true
commonAncestorContainer: #text
endContainer: #text
endOffset: 0
startContainer: #text
startOffset: 0
__proto__: Range
// после:
Range {commonAncestorContainer: text, collapsed: true, endOffset: 0, endContainer: text, startOffset: 0…}
collapsed: true
commonAncestorContainer: #text
endContainer: #text
endOffset: 0
startContainer: #text
startOffset: 0
__proto__: Range
как предотвратить?