【发布时间】:2014-01-07 17:45:25
【问题描述】:
我正在使用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/
为什么,当我备份范围并想在以后恢复它时,它不起作用?我需要以其他方式备份范围吗?
【问题讨论】:
-
您没有创建范围的“备份”,您需要
cloneRange()来复制范围。 -
@Teemu 你能举个例子吗?
-
Here... 虽然在改变背景时有些奇怪,但在模糊和重新聚焦窗口后它会改变。
标签: javascript range contenteditable execcommand