角度2:获取HTML元素的位置
31687 观看
3回复
我正在尝试在Angular 2中实现自定义指令,以移动任意HTML元素。到目前为止,一切工作正常,除了我现在不单击该元素并想要开始移动时如何获取该HTML元素的初始位置。我通过这两个主机绑定将其绑定到HTML元素的top
和left
样式:
/** 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元素的当前位置。
回应 (3)
19像
<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
作者: Günter Zöchbauer 发布者: 03.03.2017 10:184像
在typeScript中,您可以获得以下位置:
@ViewChild('ElementRefName') element: ElementRef;
const {x, y} = this.element.nativeElement.getBoundingClientRect();
作者: William Perez Herrera
发布者: 04.12.2018 03:44
2像
在html中:
<div (click)="getPosition($event)">xxx</div>
在打字稿中:
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 }
}
作者: mohammad ali
发布者: 21.09.2018 01:53
来自类别的问题 :
- html5 HTML 4和HTML 5之间的主要区别是什么?
- html5 HTML文本输入仅允许数字输入
- html5 我应该使用'name'或'id'制作HTML Anchor吗?
- html5 我应该将输入元素放在标签元素内吗?
- html5 HTML 5 <video>标记与Flash视频。优缺点都有什么?
- html5 比较/对比HTML,XHTML,XML和HTML5
- angular 如何查看我使用的Angular版本?
- angular AngularJS:如何清除URL中的查询参数?
- angular angular:根据模型中的布尔值切换按钮文本
- angular Angular 2:是否强制使用括号/方括号?
- angular 在最新的TypeScript(大概是v1.5)示例中,@(符号)是什么意思?
- angular Angular 2.0绑定到样式的值
- angular2-hostbinding AoT编译中的Angular2主机绑定问题
- angular2-hostbinding 在Angular 2中使用@HostBinding对模板子元素进行mouseenter / mouseleave时更改主机类
- angular2-hostbinding 角度2:获取HTML元素的位置
- angular2-hostbinding 使用angular2 @HostListener时onbeforeunload确认对话框不显示
- angular2-hostbinding 角@Hostbinding不起作用
- angular2-hostbinding 在Angular 4中将属性指令应用于组件