Delphi Webbrowser scrollIntoView(true)无效

时间:2016-10-14 18:26:59

标签: delphi scroll twebbrowser

我正在尝试使用Delphi 2010在webbrowser中找到一个文本并滚动到它。代码找到文本并滚动到它,但文本保留在webview的底部(在最后一行)。我想在webview的顶部(第一行)显示文本。

我认为这个代码的代码是“scrollIntoView(true)”,但它并不影响我正在尝试做的事情。

我该怎么办?谢谢。这是我的代码

procedure TForm1.SpeedButton10Click(Sender: TObject);
var
    doc: IHTMLDocument2;
    selection: IHTMLSelectionObject;
    textRange: IHtmlTxtRange;
    scrollpos: Integer;
    Art : string;
begin

Doc := WebBrowser1.Document as IHTMLDocument2;
Selection := Doc.Selection;
TextRange := selection.createRange as IHTMLTxtRange;

Art := edit2.Text;

TextRange.collapse(false);
if TextRange.findText(Art) then
begin
TextRange.select;
TextRange.scrollIntoView(true);

 end;
end;

1 个答案:

答案 0 :(得分:2)

我也无法让TextRange.scrollIntoView(True)工作。但是,下面的代码似乎适用于格式为

的文档
  

线路1   
2号线   
3号线   
线路4   5号线
  
...   
100号线

如果文档未滚动到Line100高于浏览器窗口底线的位置。 f.i.工作正常,找到Line20并将其放在浏览器窗口的顶部。

正如您所看到的,它的工作原理是从IHTMLTextRangeMetrics获取TextRange接口并使用其offsetTop属性垂直滚动doc2的父窗口。

代码:

//  doc2 is a field of Form1 of type `IHTMLDocument2`
procedure TForm1.FindText(Text : String);
var
  selection: IHTMLSelectionObject;
  textRange: IHtmlTxtRange;
  scrollpos: Integer;
  Metrics : IHTMLTextRangeMetrics;
begin

  Selection := Doc2.Selection;
  TextRange := selection.createRange as IHTMLTxtRange;

  TextRange.collapse(false);
  if TextRange.findText(Text, 1, 0) then begin
    TextRange.select;
    TextRange.scrollIntoView(True);
    TextRange.QueryInterface(IHTMLTextRangeMetrics, Metrics);
    if Metrics <> Nil then
      doc2.parentWindow.scrollBy(0, Metrics.offsetTop);
  end;
end;