我尝试使用webBrowser1.Document.Body.ScrollTop
和webBrowser1.Document.Body.ScrollLeft
,但它们不起作用。它们总是返回0,我无法访问webBrowser1.Document.documentElement.ScrollTop
和.ScrollLeft
。
我尝试使用webBrowser1.Document.Body.ScrollTop
和webBrowser1.Document.Body.ScrollLeft
,但它们不起作用。它们总是返回0,我无法访问webBrowser1.Document.documentElement.ScrollTop
和.ScrollLeft
。
好的,我解决了:
Dim htmlDoc As HtmlDocument = wb.Document
Dim scrollTop As Integer = htmlDoc.GetElementsByTagName("HTML")(0).ScrollTop
ScrollIntoView
方法非常有效。例如,要滚动到页面的左上角。 this.webBrowser.Document.Body.FirstChild.ScrollIntoView(true);
ScrollTop
和ScrollLeft
仅允许在元素边界和其内容之间提供偏移量。似乎没有办法通过这些值来操作滚动。相反,您必须使用ScrollIntoView
。对于任何感兴趣的人,这是与Marc答案等效的C#代码:
System.Windows.Forms.HtmlDocument htmlDoc = webBrowser.Document;
if (htmlDoc != null)
{
int scrollTop = htmlDoc.GetElementsByTagName("HTML")[0].ScrollTop;
int scrollLeft = htmlDoc.GetElementsByTagName("HTML")[0].ScrollLeft;
}
if (this.webBrowser.Document != null)
{
int scrollPosition = this webBrowser.Document.Body.ScrollTop;
}
被接受的答案是VB。对于C# WPF WebBrowser,我不得不写以下内容。不知道我是否真的需要所有这些转换。如果能够摆脱其中任何一个转换,那将是非常好的。
using mshtml;
int? GetScrollTop(System.Windows.Controls.WebBrowser browser)
{
object doc = browser.Document;
HTMLDocument castDoc = doc as HTMLDocument;
IHTMLElementCollection elements = castDoc?.getElementsByTagName("HTML");
IEnumerator enumerator = elements?.GetEnumerator();
enumerator?.MoveNext();
var first = enumerator?.Current;
IHTMLElement2 castFirst = first as IHTMLElement2;
int? top = castFirst?.scrollTop;
return top;
}
documentElement
。IHTMLElement2 page =
(wb.Document.DomDocument as IHTMLDocument3).documentElement as IHTMLElement2;
int pos = page.scrollTop;
我发现 Kurt 的答案几乎可以用,但是必须将数组引用更改为以下内容:
var document = (HTMLDocument)Browser.Document;
var scrollTop = (int)document.getElementsByTagName("HTML").item(0).ScrollTop;