我有一个组件MyWrapper
,它由左侧的流动文本和右侧的边距组成。在页边距中,有一些MarginElement
组件应该与<mark>
文本中的标签垂直对齐。
import {html, css, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';
@customElement('my-wrapper')
export class MyWrapper extends LitElement {
static styles = css`:host{display:flex}`
render() {
return html`
<p>
<mark id="mark1">Lorem</mark> ipsum dolor sit amet, consectetur adipiscing elit, sed
do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco
laboris nisi ut aliquip ex ea commodo consequat. Duis aute
irure dolor in reprehenderit in voluptate velit esse <mark id="mark2">cillium</mark>.
</p>
<div class="margin" style="width:50%">
<margin-element id="m1" related-element-id="mark1">Some note</margin-element>
<margin-element id="m2" related-element-id="mark2">Some other note</margin-element>
</div>`;
}
updated(){this.positionMargin()}
positionMargin() {
const elements = this.shadowRoot.querySelectorAll('margin-element')
elements.forEach(el => {
const relatedElement = this.shadowRoot.querySelector(`#${el.relatedElementId}`)
el.style.top = relatedElement.getBoundingClientRect().top + 'px'
})
}
}
@customElement('margin-element')
export class MarginElement extends LitElement {
static styles = css`:host {position: absolute; border: 1px solid red;}`
@property({type: String, attribute: 'related-element-id'}) relatedElementId: string
render() {return html`<slot></slot>`}
}
我想在positionMargin()
渲染MyWrapper
完成后运行该函数,但我知道调用relatedElement.getBoundingClientRect()
margin-element
本身必须被渲染。查看文档updated()
似乎是最好的电话positionMargin()
。然而,似乎到那<margin-element>
时还没有渲染 child 。因此,getBoundingClientRect()
不可用。
如何解决?