角度2:获取HTML元素的位置 [英] Angular 2: Get position of HTML element
问题描述
我正在尝试在Angular 2中实现自定义指令,以移动任意HTML元素.到目前为止,一切工作正常,只是我现在不单击并想要开始移动时如何获取HTML元素的初始位置.我使用这两个主机绑定将HTML元素的top
和left
样式绑定:
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 top
and left
styles of my HTML element with those two host bindings:
/** 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;
问题在于,它们两个开头都是undefined
.我只能更新也会更新HTML元素的值,但无法阅读吗?那是那样吗?如果是的话,我还必须采用什么替代方法来检索HTML元素的当前位置.
The problem is that both of them are undefined
at 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.
推荐答案
<div (click)="move()">xxx</div>
// get the host element
constructor(elRef:ElementRef) {}
move(ref: ElementRef) {
console.log(this.elRef.nativeElement.offsetLeft);
}
另请参见 https://stackoverflow.com/a/39149560/217408
这篇关于角度2:获取HTML元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!