getting absolute position of HTML element in webbrowser control with C#

后端 未结 7 1268
萌比男神i
萌比男神i 2021-02-04 07:39

I was wondering if its possible to get the absolute position of specific HTML element I have loaded in webbrowser control with C#.

I tried almost all of the options that

7条回答
  •  灰色年华
    2021-02-04 08:08

    here is the solution I got so far:

    // set the size of our web browser to be the same size as the image int width, height; width = webBrowser1.Document.Images[0].ClientRectangle.Width; height = webBrowser1.Document.Images[0].ClientRectangle.Height;

    webBrowser1.Width = width;
    webBrowser1.Height = height;
    
    //scroll vertically to that element
    webBrowser1.Document.Images[0].OffsetParent.ScrollIntoView(true);
    
    //calculate x, y offset of the element
    int x = webBrowser1.Document.Images[s].OffsetRectangle.Left + 
    webBrowser1.Document.Images[s].OffsetParent.OffsetRectangle.Left + 
    webBrowser1.Document.Images[s].OffsetParent.OffsetParent.OffsetRectangle.Left+
    webBrowser1.Document.Images[s].OffsetParent.OffsetParent.OffsetParent.OffsetRectangle.Left+
    webBrowser1.Document.Images[s].OffsetParent.OffsetParent.OffsetParent.OffsetParent.OffsetRectangle.Left;
    
    int y = webBrowser1.Document.GetElementsByTagName("HTML")[0].ScrollTop;
    
    //now scroll to that element
    webBrowser1.Document.Window.ScrollTo(x, y);
    

    now this code works perfectly.. but there is an issue with calculating the offsets. I need to calculate the offsetparent of the element then calculate the offsetparent of the offsetparent etc.. I need to do that dynamically not adding it one by one.. I don't know how to do that. any ideas?

    EDIT: here is my last and final version and it works with any html element it will find the absolute position of any element I want..

       public int getXoffset(HtmlElement el)
         {
             //get element pos
             int xPos = el.OffsetRectangle.Left;
    
             //get the parents pos
             HtmlElement tempEl = el.OffsetParent;
             while (tempEl != null)
             {
                 xPos += tempEl.OffsetRectangle.Left;
                 tempEl = tempEl.OffsetParent;
             }
    
             return xPos; 
         }  
    
         public int getYoffset(HtmlElement el)
         {
             //get element pos
             int yPos = el.OffsetRectangle.Top;
    
             //get the parents pos
             HtmlElement tempEl = el.OffsetParent;
             while (tempEl != null)
             {
                 yPos += tempEl.OffsetRectangle.Top;
                 tempEl = tempEl.OffsetParent;
             }
    
             return yPos;
         }
    

    then use the position with:

     //now scroll to that element
     webBrowser1.Document.Window.ScrollTo(x, y);
    

    done!

提交回复
热议问题