如何在 TWebBrowser 中更改字体?

WeG*_*ars 2 delphi font-face twebbrowser

这个问题与:在 TWebBrowser 中加载字符串(HTML 代码)的最佳方法是什么?

我正在尝试使用 doc.body.style.fontFamily 更改 TWebBrowser 中的字体,但没有任何反应。字体仍然是 TimesNewRoman。

procedure THTMLEdit.SetHtmlCode(CONST HTMLCode: string);
VAR
   Doc: Variant;
begin
 if NOT Assigned(wbBrowser.Document)
 then wbBrowser.Navigate('about:blank');

 WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE
   DO Application.ProcessMessages;

 Doc := wbBrowser.Document;
 Doc.Clear;
 Doc.Write(HTMLCode);
 doc.body.style.fontFamily:='Arial'; <------ won't work
 Doc.DesignMode := 'On';
 Doc.Close;
end;
Run Code Online (Sandbox Code Playgroud)

kob*_*bik 5

关闭文档后需要再次让文档交互。例如:

procedure TForm1.SetHtmlCode(CONST HTMLCode: string);
VAR
   Doc: Variant;
begin
  if NOT Assigned(wbBrowser.Document)
  then wbBrowser.Navigate('about:blank');

  //WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE // not really needed
  //DO Application.ProcessMessages;

  Doc := wbBrowser.Document;
  //Doc.Clear; // not needed
  Doc.Write(HTMLCode);
  Doc.Close; 
  Doc.DesignMode := 'On';

  WHILE wbBrowser.ReadyState < READYSTATE_INTERACTIVE
  DO Application.ProcessMessages;

  doc.body.style.fontFamily:='Arial';

  ShowMessage(doc.body.outerHTML); // test it
end;
Run Code Online (Sandbox Code Playgroud)

但我认为最好的方法是处理OnDocumentComplete你知道你有一个有效文档/正文的地方,并设置样式或其他需要的东西。

  • 不客气。`TWebBrowser` 是异步处理和事件驱动的。切换到 `OnDocumentComplete` 最终会让你的生活更轻松,并且(希望)没有错误。 (3认同)