代码之家  ›  专栏  ›  技术社区  ›  johnc

C导航到WebBrowser控件中的锚

  •  9
  • johnc  · 技术社区  · 16 年前

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

    XSLT正在输出的HTML中写出<a>标记,以允许WebBrowser控件导航到选定的历史记录条目。

    因为我们不是严格意义上的“导航”到HTML,而是通过文档文本设置HTML,所以我不能用anchorname“导航”到所需的锚,因为WebBrowser的URL为空(编辑:实际上完成时,它是关于:空的)。

    在这种情况下,如何动态导航到Web浏览器控件的HTML中的定位标记?

    编辑:

    感谢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;
                }
            }
        }
    
    2 回复  |  直到 9 年前
        1
  •  10
  •   sdolphin    16 年前

    我相信有人会有更好的方法来完成这项任务,但这里是我用来完成这项任务的方法。

    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;
       }
    }
    
        2
  •  5
  •   dbooher    9 年前

    我知道这个问题由来已久,有一个很好的答案,但还没有人提出这个问题,所以它可能对来这里寻求答案的其他人有用。

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

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

    然后你可以用

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

    其中WebBrowserReview是WebBrowser控件。

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

    推荐文章