【问题标题】:C# Navigate to Anchors in WebBrowser controlC# 导航到 WebBrowser 控件中的锚点
【发布时间】:2010-11-29 08:24:52
【问题描述】:

我们的 Winforms 应用程序中有一个 Web 浏览器,可以很好地显示 xslt 呈现的选定项目的历史记录。

xslt 正在输出的 html 中写出 标记,以允许 webBrowser 控件导航到选定的历史条目。

由于我们不是在严格的网络意义上“导航”到 html,而是通过 DocumentText 设置 html,因此我无法使用#AnchorName“导航”到所需的锚点,因为 webBrowser 的 Url 为空(编辑:实际上在完成时它是关于:空白)。

在这种情况下,如何动态导航到 Web Browser 控件的 html 中的 Anchor 标记?

编辑:

感谢 sdolphion 的提示,这是我最终使用的代码

void _history_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        _completed = true;
        if (!string.IsNullOrEmpty(_requestedAnchor))
        {
            JumpToRequestedAnchor();
            return;
        }
    }

    private void JumpToRequestedAnchor()
    {
        HtmlElementCollection elements = _history.Document.GetElementsByTagName("A");
        foreach (HtmlElement element in elements)
        {
            if (element.GetAttribute("Name") == _requestedAnchor)
            {
                element.ScrollIntoView(true);
                return;
            }
        }
    }

【问题讨论】:

    标签: c# winforms webbrowser-control


    【解决方案1】:

    我确信有人有更好的方法来做这件事,但这是我用来完成这项任务的方法。

    HtmlElementCollection elements = this.webBrowser.Document.Body.All;
    foreach(HtmlElement element in elements){
       string nameAttribute = element.GetAttribute("Name");
       if(!string.IsNullOrEmpty(nameAttribute) && nameAttribute == section){
          element.ScrollIntoView(true);
          break;
       }
    }
    

    【讨论】:

    • 刚刚在网上找到了一个参考,现在正在测试它。确认后将标记为答案。
    • 虽然我使用的是 Document.GetElementByName 而不是循环
    • 感谢您发回您的更新,我更改了我的更新以更接近您的更新。
    【解决方案2】:

    我知道这个问题已经过时并且有很好的答案,但还没有建议,所以它可能对其他来这里寻找答案的人有用。

    另一种方法是使用 HTML 中的元素 ID。

    <p id="section1">This is a test section</p>

    然后就可以使用了

    HtmlElement sectionAnchor = webBrowserPreview.Document.GetElementById("section1");
    if (sectionAnchor != null)
    {
        sectionAnchor.ScrollIntoView(true);
    }
    

    其中 webBrowserPreview 是您的 WebBrowser 控件。

    或者,sectionAnchor.ScrollIntoView(false) 只会将元素显示在屏幕上,而不是将其与页面顶部对齐

    【讨论】:

    • 原谅我的无知。 webBrowserPreview 是在哪里定义的?
    • 哇,真不敢相信我错过了,之前没有人注意到。它是表单中的 WebBrowser 控件。我已在我的回答中添加了说明。
    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-09
    相关资源
    最近更新 更多