在Dart中获取Element的全局/文档坐标(又名$('some').offset())

dee*_*lue 5 dom dart

我试图在Dart中获取元素(DOM元素)的文档(全局)坐标,在纯JavaScript中我可以通过jQuery使用$('some_selector').offset()获得.

我一直在浏览Dart dart:html API,但到目前为止还没有运气.

有任何想法吗?谢谢

Ale*_*uin 6

Element上没有原生函数来获取坐标.

这是dart的jQuery.offset()版本:

class Position {
  num left, top;
  Position(this.left, this.top);
}

Position offset(Element elem) {
  final docElem = document.documentElement;
  final box = elem.getBoundingClientRect();
  return new Position(box.left + window.pageXOffset - docElem.clientLeft,
                      box.top  + window.pageYOffset - docElem.clientTop);
}
Run Code Online (Sandbox Code Playgroud)

另一个解决方案是通过js-interop使用jQuery.offset():

Position jQueryOffset(Element elem) {
  return js.scoped((){
    final offset = js.context.jQuery(elem).offset();
    return new Position(offset.left, offset.top);
  });
}
Run Code Online (Sandbox Code Playgroud)