procedure Focus(Document:IHTMLDocument2);
var IDisp:IDispatch;
pElement:IHTMLElement;
i:integer;
begin
for I := 0 to Document.all.length - 1 do // 遍历所有HTML元素
begin
{得到当前的IDispatch接口}
IDisp:=Document.all.item(i,i);
IDisp.QueryInterface(IID_IHTMLElement,pElement);
if CompareText(pElement.tagName,'INPUT')=0 then
begin
Document.parentWindow.execScript(Format('document.all(%d).focus();',[i]),'JScript');
{执行JavaScript,将焦点移动到该元素上}
exit;
end;
end; // for
end;
procedure Focus(Document:IHTMLDocument2);
var IDisp:IDispatch;
pElement:IHTMLElement;
i:integer;
sID:string;
hasID:boolean;
begin
hasID:=false;
for I := 0 to Document.all.length - 1 do // 遍历所有HTML元素
begin
{得到当前的IDispatch接口}
IDisp:=Document.all.item(i,i);
IDisp.QueryInterface(IID_IHTMLElement,pElement);
if CompareText(pElement.tagName,'INPUT')=0 then
begin
hasID:=Length(pElement.id )>0;//如果该元素没有ID
if not hasID then pElement.id :='AZXUEJFLAIER34';//设置一个新的ID
sID:=pElement.id ;
Document.parentWindow.execScript(Format('%s.focus();',[sID]),'JScript');
{执行JavaScript,将焦点移动到该元素上}
if not hasID then pElement.id :='';//恢复原来的ID.
exit;
end;
end; // for
end;
举个例子:
procedure TForm1.FormCreate(Sender: TObject);
begin
WebBrowser1.Navigate('about:<INPUT%20TYPE="TEXT">');
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Focus(WebBrowser1.Document as IHTMLDocument2);
end;