如何在Web浏览器控件中找到元素的位置?

ugl*_*and 6 c# webbrowser-control winforms

我有一个带有Web浏览器控件的表单,它加载一个网页(工作正常,页面加载正常)

现在我的问题是,我想找到一个特定的url-link是在折叠之下还是在折叠之上(我的意思是,用户是否必须向下滚动才能看到这个链接),这个v是否在滚动时是可见的或者我们需要滚动才能看到它..我希望我很清楚

我做了大量的搜索,但看起来没有关于查找html元素位置的信息(在当前视图的上方或下方)

有没有人对此有所了解并能指出我正确的方向吗?(我正在寻找c#解决方案 - WinForms)

更新:非常感谢John Koerner的代码.真的很感激他在解决我的问题上花费的时间和精力.

还有Jonathan和其他所有人......我希望我能将Jonathans的回复标记为答案,但它只允许将一个回复标记为答案.他的评论也很清楚,也很有用.谢谢你们真棒!

Joh*_*ner 7

好吧,我已经在谷歌和stackoverflow上测试了它,它似乎工作:

private bool isElementVisible(WebBrowser web, string elementID)
{

    var element = web.Document.All[elementID];

    if (element == null)
        throw new ArgumentException(elementID + " did not return an object from the webbrowser");

    // Calculate the offset of the element, all the way up through the parent nodes
    var parent = element.OffsetParent;
    int xoff = element.OffsetRectangle.X;
    int yoff = element.OffsetRectangle.Y;

    while (parent != null)
    {
        xoff += parent.OffsetRectangle.X;
        yoff += parent.OffsetRectangle.Y;
        parent = parent.OffsetParent;
    }

    // Get the scrollbar offsets
    int scrollBarYPosition = web.Document.GetElementsByTagName("HTML")[0].ScrollTop;
    int scrollBarXPosition = web.Document.GetElementsByTagName("HTML")[0].ScrollLeft;

    // Calculate the visible page space
    Rectangle visibleWindow = new Rectangle(scrollBarXPosition, scrollBarYPosition, web.Width, web.Height);

    // Calculate the visible area of the element
    Rectangle elementWindow = new Rectangle(xoff,yoff,element.ClientRectangle.Width, element.ClientRectangle.Height);

    if (visibleWindow.IntersectsWith(elementWindow))
    {
        return true;
    }
    else
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用它,你只需调用:

isElementVisible(webBrowser1, "topbar")  //StackOverflow's top navigation bar
Run Code Online (Sandbox Code Playgroud)