テキストを使用contenteditable
して強調表示しています。次に、そのテキスト範囲をバックアップし、後でその範囲(テキスト)に別の色を付けたいと思います。メソッドをチェックインするとzss_editor.restorerange
、有効なオブジェクトが返されるselection
ため、以前にその範囲を保存していた方法が間違っているに違いありません。
var zss_editor = {};
// The current selection
zss_editor.currentSelection;
zss_editor.backuprange = function(){
var selection = window.getSelection();
zss_editor.currentSelection = selection.getRangeAt(0);
zss_editor.currentSelection.setEnd(zss_editor.currentSelection.startContainer, zss_editor.currentSelection.startOffset);
}
zss_editor.restorerange = function(){
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(zss_editor.currentSelection);
console.log(zss_editor.currentSelection);
}
zss_editor.setTextColor = function(color) {
zss_editor.restorerange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('foreColor', false, color);
document.execCommand("styleWithCSS", null, false);
}
zss_editor.setBackgroundColor = function(color) {
zss_editor.restorerange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('hiliteColor', false, color);
document.execCommand("styleWithCSS", null, false);
}
JS Fiddle での作業例: http://jsfiddle.net/zedsaid/gC3jq/11/
範囲をバックアップして後で復元したい場合、なぜ機能しないのですか? 別の方法で範囲をバックアップする必要がありますか?