突出显示DOM范围元素的文本, [英] highlight the text of the DOM range element,
问题描述
我可以突出显示HTML页面上的文字(通过gtkmozembed呈现),如下所示。
I am able to highlight the text on the HTML page(rendered through gtkmozembed), which is selected, like below.
var range, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
document.designMode = "on";
if (range) {
sel.removeAllRanges();
sel.addRange(range);
}
document.execCommand("HiliteColor", false, colour);
document.designMode = "off";
}
嗯,它工作得非常好。现在我试图存储信息( startNode,startOffset,endNode,endOffset)关于突出显示的文本,下次当我打开同一页面时,突出显示相同的文本。
我能够成功存储信息并在同一页面打开时检索它们。
我试图使用以下代码突出显示文本。
Well,it works very fine.Now i am trying to store the information(startNode, startOffset,endNode, endOffset) about the highlighted text, and next time when i open the same page,highlight the same text. I am able to successfully store the info and retrieve them when the same page opens. And i am trying to highlight the text using following code.
var range = document.createRange();
range.setStart(startNode, startOffset);
range.setEnd(endNode, endOffset);
document.designMode = "on";
range.execCommand("HiliteColor", false, colour);
document.designMode = "off";
但它没有按照我的预期运作。任何人都可以帮助我达到要求吗?谢谢...
But it is not working as i am expecting. Can anyone help me to achieve the required? Thanks...
推荐答案
execCommand
方法是一种方法文件,而不是范围。此外, hilitecolor
仅适用于Firefox,因此您应该回到在WebKit和Opera中使用 backcolor
。
The execCommand
method is a method of the document, not the Range. Also, hilitecolor
only works in Firefox, so you should fall back to using backcolor
in WebKit and Opera.
更新
已在IE 9中修复。
function makeEditableAndHighlight(colour) {
var sel = window.getSelection();
var range = null;
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, sel;
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);
}
}
这篇关于突出显示DOM范围元素的文本,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!