Angular 2:获取 HTML 元素的位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42576008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:28:15  来源:igfitidea点击:

Angular 2: Get position of HTML element

htmlangularangular2-hostbinding

提问by tzwickl

I'm trying to implement a custom directive in Angular 2 for moving an arbitrary HTML element around. So far everything is working except that I don't now how to get the initial position of the HTML element when I click on it and want to start moving. I'm binding to the topand leftstyles of my HTML element with those two host bindings:

我正在尝试在 Angular 2 中实现一个自定义指令,用于移动任意 HTML 元素。到目前为止,一切正常,只是我现在不知道如何在单击 HTML 元素并开始移动时获取它的初始位置。我使用这两个主机绑定绑定到我的 HTML 元素的topleft样式:

/** 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;

The problem is that both of them are undefinedat the beginning. I can only update the values which will also update the HTML element but I cannot read it? Is that suppose to be that way? And if yes what alternative do I have to retrieve the current position of the HTML element.

问题是,两者都undefined处于起步阶段。我只能更新也会更新 HTML 元素的值,但我无法读取它?应该是这样吧?如果是的话,我有什么替代方法可以检索 HTML 元素的当前位置。

回答by Günter Z?chbauer

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

move(ref: ElementRef) {
  console.log(this.elRef.nativeElement.offsetLeft);
}

See also https://stackoverflow.com/a/39149560/217408

另见https://stackoverflow.com/a/39149560/217408

回答by William Perez Herrera

In typeScript you can get the position as follows:

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

@ViewChild('ElementRefName') element: ElementRef;

const {x, y} = this.element.nativeElement.getBoundingClientRect();

回答by mohammad ali

in html:

在 html 中:

<div (click)="getPosition($event)">xxx</div>

in typescript:

在打字稿中:

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 }
}