首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi TWebBrowser 與 MSHTML 深度解析 (5):IHTMLDocument 接口完整參考

     編輯:Delphi

前言

在 Delphi 中使用 TWebBrowser 控件進行網頁自動化或內容處理時,核心在於操作 MSHTML DOM 模型。IHTMLDocument 系列接口(從 IHTMLDocument2 到 IHTMLDocument5)提供了對文檔結構、樣式、選區、事件等全方位的控制能力。本文系統整理了這些接口的方法、屬性與事件,供開發者快速查閱與實戰參考。

IHTMLDocument2:核心文檔操作接口

作為最基礎且常用的文檔接口,IHTMLDocument2 涵蓋了文檔流控制、元素集合訪問、樣式表管理、命令執行等核心功能。

主要方法

  • write / writeln:向文檔流寫入 HTML 內容,後者自動換行。
  • open / close:打開輸出流以接收 write 內容,關閉並輸出流。
  • clear:清空文檔所有元素(注意:部分版本可能暫不支持)。
  • queryCommand* 系列:queryCommandSupported、Enabled、State、Indeterm、Text、Value,用於檢查編輯命令狀態。
  • execCommand / execCommandShowHelp:執行編輯命令(如粗體、複製)及顯示幫助。
  • createElement:動態創建 HTML 元素節點。
  • elementFromPoint:獲取指定坐標下的元素。
  • createStyleSheet:創建樣式表對象。

核心屬性集合

提供對各類元素的集合式訪問:

  • all:所有元素集合
  • images、applets、links、forms、anchors、scripts、frames、embeds、plugins、styleSheets

文檔資訊屬性

  • title、body、activeElement、designMode、selection、readyState
  • 顏色屬性:linkColor、alinkColor、vlinkColor、bgColor、fgColor
  • URL 相關:referrer、location、url、domain
  • 其他:cookie、charset、mimeType、fileSize、security、protocol、parentWindow

常用事件

涵蓋滑鼠、鍵盤、選區、拖放、數據綁定、錯誤處理等:onclick、ondblclick、onmousedown/up/move/over/out、onkeypress/down/up、onreadystatechange、onselectstart、ondragstart、onbeforeupdate/afterupdate/errorupdate 等。

IHTMLDocument3:進階文檔操作

新增方法

  • recalc:重新計算動態屬性
  • releaseCapture:釋放滑鼠捕獲

新增屬性

  • createTextNode、attachEvent/detachEvent、createDocumentFragment
  • 元素查詢:getElementsByName、getElementById、getElementsByTagName
  • documentElement(根節點)、uniqueID、dir、parentDocument、baseUrl

新增事件

數據綁定相關:onrowsdelete、onrowsinserted、oncellchange、ondatasetchanged、ondataavailable、ondatasetcomplete、onpropertychange、oncontextmenu、onstop。

IHTMLDocument4:焦點與渲染控制

方法

  • focus / hasFocus:焦點控制
  • createDocumentFromUrl:下載並返回文檔接口
  • CreateEventObject / FireEvent:自定義事件觸發

屬性

  • createRenderStyle、namespaces、media、URLUnencoded

事件

  • onselectionchange、oncontrolselect

IHTMLDocument5:DOM Level 2/3 擴展

方法

  • createAttribute、createComment

屬性

  • doctype、implementation_、compatMode(返回 BackCompat 或 CSS1Compat)

事件

  • onmousewheel、onfocusin/out、onactivate/deactivate、onbeforeactivate/beforedeactivate

實戰提示

  1. 在 Delphi 中使用需引用 MSHTML 單元,介面變量聲明為 IHTMLDocument2 以上類型。
  2. 通過 (WebBrowser1.Document as IHTMLDocument2) 獲取接口實例。
  3. 事件處理建議使用 attachEvent/detachEvent 而非直接賦值,避免覆蓋現有處理程序。
  4. designMode = 'On' 可開啟所見即所得編輯模式,配合 execCommand 實現富文本編輯器。

掌握這些接口細節,能讓你在 Delphi 中像操作 JavaScript DOM 一樣靈活控制網頁內容,構建強大的網頁自動化、內容提取、測試工具或嵌入式瀏覽器應用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved