Angular 2

时间:2017-09-21 10:13:56

标签: javascript angular offset

那么,如何在Angular 2中通过ID获取一些元素偏移?

做到这一点:

scrollToBottom () { let content = document.getElementById('content') let offsetTop = content.getBoundingClientRect().top console.log(content, offsetTop) }

但我收到此错误:Object is possibly 'null'.请求帮助。

1 个答案:

答案 0 :(得分:0)

因为html中没有此id的元素。只需签入if statement;

scrollToBottom () {
let content = document.getElementById('content')
if (content) {
   let offsetTop = content.getBoundingClientRect() ? content.getBoundingClientRect().top : 0
   console.log(content, offsetTop)
 }

}