【问题标题】:Getting incorrect values for element's position from clientLeft, clientTop, offsetLeft, and offsetTop从 clientLeft、clientTop、offsetLeft 和 offsetTop 获取元素位置的错误值
【发布时间】:2017-07-11 22:14:12
【问题描述】:

我正在尝试返回元素的位置,但由于某种原因,左侧和顶部的客户端、滚动和偏移值总是错误的。这里的目标是确定用户是否在下拉元素之外单击,如果关闭它,因此我需要元素的准确位置来与单击位置进行比较。

例如,我使用标尺检查了元素的位置,它读取的左侧值为 1013 像素,顶部值为 484 像素。但是,当我在代码中获取元素并检查 offsetLeft 时,值是 3,offsetTop 是 16。这是怎么回事?似乎我正在获取相对于父级而不是文档的位置。

我使用 angular 并使用组件中的模板引用获取元素。

dropdown.component.ts

@ViewChild('dropdown') dropdown: any; // Template reference to the element

constructor(
  private elementRef: ElementRef // Reference to the :host element
} { }

ngOnDestroy() {
  this.elementRef.nativeElement.removeEventListener('click', this.handleClick.bind(this));
}

ngOnInit() {
  this.subscribeToClickEvent();
}

private handleClick(event: MouseEvent): void {
  // this.dropdown.nativeElement.clientLeft equals 0
  // this.dropdown.nativeElement.clientTop equals 0
  // this.dropdown.nativeElement.offsetLeft equals 3
  // this.dropdown.nativeElement.offsetTop equals 16
  // this.dropdown.nativeElement.scrollLeft equals 0
  // this.dropdown.nativeElement.scrollTop equals 0
  // Left should equal ~1013 and top should equal ~484
}

private subscribeToClickEvent(): void {
  this.elementRef.nativeElement.addEventListener('click', this.handleClick.bind(this));
}

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您必须使用 element.getBoundingClientRect() 来获取准确的位置。

    【讨论】:

    • 我认为我不需要添加任何内容,getBoundingClientRect 似乎提供了更准确的位置日期。您应该将答案更新为使用 getBoundingClientRect
    猜你喜欢
    • 2017-06-11
    • 1970-01-01
    • 2012-02-04
    • 2022-10-06
    • 2015-01-27
    • 2020-02-22
    • 2015-10-07
    • 2017-04-22
    • 2010-11-05
    相关资源
    最近更新 更多