【发布时间】:2020-03-22 19:49:27
【问题描述】:
这是我的自定义元素。
class ContextMenu extends HTMLElement {
constructor() {
super()
}
connectedCallback() {
console.log(this.getBoundingClientRect()) // empty
console.log(this.offsetWidth) // 0
console.log(this.offsetHeight) // 0
setTimeout(() => {
console.log(this.getBoundingClientRect()) // good
console.log(this.offsetWidth) // good
console.log(this.offsetHeight) // good
}, 1)
}
}
document.customElements.define('context-menu', ContextMenu)
这是一个右键单击时出现的上下文菜单。我的目标是立即检查上下文菜单是否太高或太宽而无法在用户右键单击的位置显示,如果是,我会相应地进行调整。
我的问题是connectedCallback() 似乎在元素呈现在屏幕上之前运行。如果我设置一个只有 1ms 的计时器,我就会得到我需要的位置数据。
有没有原生的afterRender() 或更适合我使用的东西?我目前的方法是肉眼无法检测到的,但依赖于 CPU 功率,延长计时器会使其明显。
【问题讨论】:
-
虽然这可能是重复的,但请考虑以下在线资源,这些资源支持上述问题中接受的答案:gist.github.com/paulirish/5d52fb081b3570c81e3a 和 developer.mozilla.org/en-US/docs/Glossary/Shadow_tree
-
在
connectedCallback的end 处将自定义元素添加到DOM。setTimeout为 0 足以强制您的 JS 代码在 当前 EventLoop 完成之后运行....您的元素现在在 DOM in 中,您可以查询 DOM 相关值。所以是的,在这种你想使用 DOM 相关值的场景中,setTimeout(或requestAnimationFrame)是你唯一有效的选择。
标签: javascript html custom-element