高亮网页中的关键字

高亮网页中的关键字

javascript的代码如下

function HightLight(nWord)
{
var oRange = document.body.createTextRange();
while(oRange.findText(nWord))
{
oRange.pasteHTML("

1<span style="background-color:yellow">" + oRange.text + "</span>

");
oRange.moveStart('character',1);
}
}

如果在vb中使用,改进一下,

Public Sub HightLight2(nKey$, nDoc As MSHTML.HTMLDocument, Optional beforeTag$ = "", Optional afterTag$ = "")
On Error Resume Next
Dim tBody As MSHTML.HTMLBody
Dim oRange As MSHTML.IHTMLTxtRange

If beforeTag = "" Then
beforeTag = "

1<span style="background-color:yellow">"   
2End If   
3If afterTag = "" Then   
4afterTag = "</span>

"
End If

Set tBody = nDoc.body
If Not tBody Is Nothing Then
Set oRange = tBody.createTextRange
If Not oRange Is Nothing Then
While oRange.FindText(nKey)
Call oRange.pasteHTML(beforeTag & oRange.Text & afterTag)
Call oRange.MoveStart("character", 1)
Wend
End If
End If
End Sub

如果页面中有多个frame,那么还需要做些工作,我就不写了.

lingll
[email protected]
2004-7-5

Published At
Categories with Web编程
Tagged with
comments powered by Disqus