我建议使用
document或
TextRange的
execCommand方法,该方法就是为此目的而构建的,但通常在可编辑文档中使用。这是我对类似问题的回答:
以下应该做您想要的。在非IE浏览器中,它会打开designMode,应用背景色,然后再次关闭designMode。
更新
修复了在IE 9中的工作。
更新
function makeEditableAndHighlight(colour) { var range, sel = window.getSelection(); if (sel.rangeCount && sel.getRangeAt) { range = sel.getRangeAt(0); } document.designMode = "on"; if (range) { sel.removeAllRanges(); sel.addRange(range); } // Use HiliteColor since some browsers apply BackColor to the whole block if (!document.execCommand("HiliteColor", false, colour)) { document.execCommand("BackColor", false, colour); } document.designMode = "off";}function highlight(colour) { var range; if (window.getSelection) { // IE9 and non-IE try { if (!document.execCommand("BackColor", false, colour)) { makeEditableAndHighlight(colour); } } catch (ex) { makeEditableAndHighlight(colour) } } else if (document.selection && document.selection.createRange) { // IE <= 8 case range = document.selection.createRange(); range.execCommand("BackColor", false, colour); }}


