问题
This question is related to: Which is the best way to load a string (HTML code) in TWebBrowser?
Iam trying to change font in TWebBrowser with doc.body.style.fontFamily but nothing happens. The font is still 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;
回答1:
You need to let the document be interactive again after you close the document. e.g.:
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;
But I think the best way is to handle the OnDocumentComplete
where you know you have a valid document/body, and set the style or what ever else needed.
来源:https://stackoverflow.com/questions/41957051/how-to-change-font-in-twebbrowser