Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
角度2:获取HTML元素的位置_Html_Angular_Angular2 Hostbinding - Fatal编程技术网

角度2:获取HTML元素的位置

角度2:获取HTML元素的位置,html,angular,angular2-hostbinding,Html,Angular,Angular2 Hostbinding,我试图在Angular 2中实现一个自定义指令,用于移动任意HTML元素。到目前为止,一切都正常,只是我现在不知道当我单击HTML元素并想要开始移动时,如何获得它的初始位置。我使用这两个主机绑定绑定到HTML元素的顶部和左侧样式: /** current Y position of the native element. */ @HostBinding('style.top.px') public positionTop: number; /** current X position of t

我试图在Angular 2中实现一个自定义指令,用于移动任意HTML元素。到目前为止,一切都正常,只是我现在不知道当我单击HTML元素并想要开始移动时,如何获得它的初始位置。我使用这两个主机绑定绑定到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;
问题是它们在开始时都是未定义的。我只能更新也会更新HTML元素的值,但我无法读取它?是这样吗?如果是的话,我有什么选择来检索HTML元素的当前位置呢

<div (click)="move()">xxx</div>
另请参见html中的

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

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

@ViewChild('ElementRefName') element: ElementRef;

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

但是偏移量没有给出元素的相对位置?你的问题没有提到“相对”
offsetLeft
只是一个例子。其余部分与普通JavaScript中的相同,这就是为什么我将链接添加到我的答案中。我认为,一段代码+另一个答案的链接(只有一段代码和一个链接)不应该被追加投票。此解决方案不起作用。单击mat工具栏中的按钮,将返回工具栏的元素而不是按钮。请看@MarcoAltieri谢谢你的否决投票。我看不出你的评论和我的答案有什么关系。现在在Angular应用程序中测试,它给出了奇数(非常高的数字)。我不相信孩子的补偿是所有父母补偿的简单相加。我相信正确的属性是offsetParent。@Rohan是的,我正在使用offsetParent而不是parentElement,它似乎正在工作。当浏览器大小不是100%时,此解决方案不起作用当浏览器大小不是100%时,什么能起作用?
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 }
}
@ViewChild('ElementRefName') element: ElementRef;

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