Angular 2:获取HTML元素的位置

tzw*_*ckl 5 html5 angular2-hostbinding angular

我正在尝试在Angular 2中实现一个自定义指令,用于移动任意HTML元素.到目前为止一切正常,但我现在不知道如何在点击它并想要开始移动时获取HTML元素的初始位置.我结合topleft风格与这两个主机绑定我的HTML元素:

/** current Y position of the native element. */
@HostBinding('style.top.px') public positionTop: number;

/** current X position of the native element. */
@HostBinding('style.left.px') protected positionLeft: number;
Run Code Online (Sandbox Code Playgroud)

问题在于它们都undefined处于起步阶段.我只能更新也会更新HTML元素的值,但我无法读取它?那是假设那样吗?如果是,我有什么替代方法来检索HTML元素的当前位置.

Gün*_*uer 20

<div (click)="move()">xxx</div>
Run Code Online (Sandbox Code Playgroud)
// get the host element
constructor(elRef:ElementRef) {}

move(ref: ElementRef) {
  console.log(this.elRef.nativeElement.offsetLeft);
}
Run Code Online (Sandbox Code Playgroud)

另请参见/sf/answers/2740469231/

  • @MarcoAltieri感谢您的投票。我看不到您的评论与我的答案有何关系。 (2认同)

小智 10

在 html 中:

<div (click)="getPosition($event)">xxx</div>
Run Code Online (Sandbox Code Playgroud)

在打字稿中:

getPosition(event){
    let offsetLeft = 0;
    let offsetTop = 0;

    let el = event.srcElement;

    while(el){
        offsetLeft += el.offsetLeft;
        offsetTop += el.offsetTop;
        el = el.parentElement;
    }
    return { offsetTop:offsetTop , offsetLeft:offsetLeft }
}
Run Code Online (Sandbox Code Playgroud)

  • 现在在 Angular 应用程序中测试它,它给出了奇数值(非常高的数字)。我不相信孩子的抵消是所有父母抵消的简单聚合。我相信正确的属性是 offsetParent。 (4认同)
  • @Rohan是的,我正在使用offsetParent而不是parentElement,它似乎正在工作。 (2认同)

小智 6

在typeScript中,您可以获得以下位置:

@ViewChild('ElementRefName') element: ElementRef;

const {x, y} = this.element.nativeElement.getBoundingClientRect();
Run Code Online (Sandbox Code Playgroud)

  • 当浏览器不是 100% 大小时,什么会起作用? (2认同)