gpt4 book ai didi

javascript - 从 clientLeft、clientTop、offsetLeft 和 offsetTop 获取元素位置的错误值

转载 作者:行者123 更新时间:2023-11-29 21:03:57 24 4
gpt4 key购买 nike

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

例如,我使用标尺检查了元素的位置,它读取的左侧值为 1013px,顶部值为 484px。但是,当我在代码中获取元素并检查 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));
}

最佳答案

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

关于javascript - 从 clientLeft、clientTop、offsetLeft 和 offsetTop 获取元素位置的错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45045306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com