How to scroll to desired element in WebBrowser with Delphi

在Delphi里控制浏览器成为一个需求的原因是有很多文档的html文件都特别巨大,比如有100个章节,想要控制浏览器滚动到指定的章节就成为一件特别有意思的事。
要做这样一件事,很简单,只需要两步,即:
1. 找到它/Found the element
[code language=”pascal”]
uses
MSHTML, SysUtils, Variants;

function GetElementById(const Doc: IDispatch; const Id: string): IDispatch;
var
Document: IHTMLDocument2; // IHTMLDocument2 interface of Doc
Body: IHTMLElement2; // document body element
Tags: IHTMLElementCollection; // all tags in document body
Tag: IHTMLElement; // a tag in document body
I: Integer; // loops thru tags in document body
begin
Result := nil;
// Check for valid document: require IHTMLDocument2 interface to it
if not Supports(Doc, IHTMLDocument2, Document) then
raise Exception.Create(‘Invalid HTML document’);
// Check for valid body element: require IHTMLElement2 interface to it
if not Supports(Document.body, IHTMLElement2, Body) then
raise Exception.Create(‘Can”t find element’);
// Get all tags in body element (‘*’ => any tag name)
Tags := Body.getElementsByTagName(‘*’);
// Scan through all tags in body
for I := 0 to Pred(Tags.length) do
begin
// Get reference to a tag
Tag := Tags.item(I, EmptyParam) as IHTMLElement;
// Check tag’s id and return it if id matches
if AnsiSameText(Tag.id, Id) then
begin
Result := Tag;
Break;
end;
end;
end;
[/code]
2. 滚到它/do scroll
[code language=”pascal”]
function ScrollToElement(wb: TEmbeddedWB; id: String): Boolean;
var
Elem: IHTMLElement;
begin
Elem := GetElementById(wb.Document, id) as IHTMLElement;
if Assigned(Elem) then
wb.ScrollToPosition(0, Elem.offsetTop);
end;
[/code]
references:
1. Finding HTML elements by ID in a TWebBrowser document
2. 源码已经发到我在code.google.com上的小工具项目了,直接看吧/You could down the full source code at my pumpkin project hosted on code.google.com
3. Scroll view to Anchor position

发表评论

电子邮件地址不会被公开。 必填项已用*标注