angular - 如何在Angular中使用名为“dropdown”的类获取topOffset
问题描述
我在 Angular 中需要与 jQuery/HTML 相同的结果。使用 jQuery,无论是否滚动,我都会得到相同的 topOffset 值。
// get the top offset of the dropdown (distance from top of the page)
var topOffset = $(".dropdown").offset().top;
供您参考,在 Angular 中,我将模板变量与@ViewChild一起使用,但 topOffset 值已更改,并且没有提供与 jQuery 相同的所需结果。
@ViewChild('dp') dropdown: ElementRef
functionName() {
let topOffset = this.dropdown.nativeElement.getBoundingClientRect().top;
}
请在评论中告诉我,我必须做什么才能达到所需的结果。
解决方案
jQuery 是开源的,如果您在 github(此链接)中查找,您会看到
offset: function( options ) {
...
rect = elem.getBoundingClientRect();
win = elem.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};
}
如您所见,您需要添加 win.pageYOffset
所以你可以创建一个函数
getOffset(element:HTMLElement){
const rect = element.getBoundingClientRect();
const win = element.ownerDocument.defaultView;
return {
top: rect.top + win.pageYOffset,
left: rect.left + win.pageXOffset
};
}
并使用
this.offset= this.getOffset(this.dropdown.nativeElement)
你可以在这个 stackblitz中看到
推荐阅读
- c# - Excel更新查询将所有数据放在第1行
- javascript - 如何加载一次 Vue 库并在任何组件中使用
- javascript - React select v2 on space press 选择第一个值
- ajax - Ajax获取请求在json上失败
- kubernetes - 如何减少 Prometheus(Federation) 的报废时间
- python - Python:将目录结构树表示为列表列表
- javascript - 如果不确定,如何防止从标签单击中检查复选框?
- java - 使用 Github 创建新存储库返回错误
- amazon-web-services - 如何使用 AppSync 解析器和 Aurora 将可选字段插入为空?
- google-cloud-platform - GoogleCloud BigQuery 异常处理