Huan

Huan

  • NA
  • 1
  • 0

offsetHeight, offsetWidth, offsetLeft and offsetTop always return zero

Nov 17 2008 8:46 AM
Hello. I want to learn positions of all elements on a page. I do so:
  public class MsHtmlSharpParser {

    IHTMLDocument2 htmlDocument;
    public HtmlTreeNode htmlTree;

    public MsHtmlSharpParser() {
      htmlDocument = new HTMLDocumentClass();
    }
    public void LoadContent(string content) {
      htmlDocument.write(new object[] { content });
      htmlDocument.close();
      ((HTMLDocumentClass)htmlDocument).recalc(true);
      htmlTree = new HtmlTreeNode((IHTMLDOMNode)htmlDocument.body);
    }
  }



  public class HtmlTreeNode {
    public IHTMLDOMNode htmlDomNode;
    public List<HtmlTreeNode> children;

    internal HtmlTreeNode(IHTMLDOMNode htmlElement) {
      this.htmlDomNode = htmlElement;
      children = new List<HtmlTreeNode>();
      IHTMLDOMChildrenCollection collection = (IHTMLDOMChildrenCollection)htmlElement.childNodes;
      int i1, n1 = collection.length;
      for(i1=0;i1<n1;i1++)
        children.Add(new HtmlTreeNode((IHTMLDOMNode)collection.item(i1)));
    }

    public void GetAbsolutePosition(out int x, out int y, out int width, out int height) {
      if (htmlDomNode is IHTMLElement) {
        x = 0;
        y = 0;
        x = ((IHTMLElement)htmlDomNode).offsetLeft;
        y = ((IHTMLElement)htmlDomNode).offsetTop;

        IHTMLElement offsetParent = ((IHTMLElement)htmlDomNode).offsetParent;
        IHTMLDOMNode parentNode = htmlDomNode.parentNode;

        while (offsetParent != null) {
          x += offsetParent.offsetLeft;
          y += offsetParent.offsetTop;
          parentNode = ((IHTMLDOMNode)offsetParent).parentNode;
          offsetParent = offsetParent.offsetParent;
        }
        width = ((IHTMLElement)htmlDomNode).offsetWidth;
        height = ((IHTMLElement)htmlDomNode).offsetHeight;
      } else
        x = y = width = height = -1;
    }
  }

I call LoadContent to load html page and parse it. It works successifully, the object tree is built. But if I try to call GetAbsolutePosition, I will see that offsetHeight, offsetWidth, offsetLeft and offsetTop always return zero. Why is it so and how to solve this problem?

Thank you.