unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, OleCtrls, SHDocVw, MSHTML;
type TForm1 = class(TForm) WebBrowser: TWebBrowser; Button: TButton; procedure FormCreate(Sender: TObject); procedure ButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end;
var Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);begin webbrowser.Navigate('file://C:/Documents and Settings/Administrator/桌面/index.html'); //这个是我做的简单测试网页;end;
procedure TForm1.ButtonClick(Sender: TObject); var doc:ihtmldocument3; //这里用HTMLdocument也是可以的。 divs:IHTMLElementCollection; divelemen:IHTMLElement; //我的Delphi7没有IHTMLElement3,不知道为什么,所以搞了很久啊,哎~;begin doc:=webbrowser.document as iHTMLDocument3; //这里如果使用Ihtmldocument2是没有效果的,只会出错,下面代码也不能使用getElementById方法。 divelemen:=doc.getElementById('T1') as IHTMLElement;
//ShowMessage(divelemen.className);
第一种方法: //divelemen.click; //只可以把onmousedown修改为onclick;
第二种方法: WebBrowser.OleObject.document.all.item('T2',0).fireEvent('onmousedown'); //就是这个了,呵呵,fireEvent这个就是关键;
第三种方法:可以说是我原创的,呵呵,网上还没有见到过。或者是我太自大了。献丑~
OleVariant(divelemen).FireEvent('onmousedown'); //D7没有IhtmlElement3提示情况下,这样写代码简洁很多。功能一样;end;
end.
第一种方法不可取,试过你就知道 -_-! .
第二种方法最有效,关键在IHTMLElement3.FireEvent,但是,我的Delphi7没有IHTMLElement3的提示,所以用了其它代码代替了。
以下是我制作的测试网页代码,文本文件保存格式为index.html
<html><body><div id="T2" class=QMEditorBtnA οnmοusedοwn="javascript:alert('dsfsdf')" οnmοuseοver="this.style.textDecoration='underline'" title=编辑HTML源码 style="PADDING-LEFT: 0px" οnmοuseοut="this.style.textDecoration='none'" unselectable="on"><HTML></div>
<a id="T1" class="3333333" οnclick="javascript:alert('abcdefg')" href="#">123</a></body><html>