自定义 Web 组件 - 如何将其附加到的开头无论该组件在哪里使用?

发布于 2025-01-16 15:49:39 字数 434 浏览 2 评论 0原文

一个用例是

 <page-alert data-alertHeading='You are in danger' data-alertInfo ="This is a description of why you are in danger.">
 </page-alert>

通常创建一个自定义页面警报组件,模板化的 HTML 将添加到页面中使用组件代码的位置:

    this.attachShadow({mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));

但是,我想将此自定义组件附加到正文,以便它是第一个元素位于开始正文标记之后,并且始终显示在页面顶部。我怎样才能做到这一点?

A use case for this is creating a custom page alert component

 <page-alert data-alertHeading='You are in danger' data-alertInfo ="This is a description of why you are in danger.">
 </page-alert>

normally, the templated HTML would be added where the component code was used in the page with:

    this.attachShadow({mode: 'open' });
    this.shadowRoot.appendChild(template.content.cloneNode(true));

I however would like to append this custom component to the body so that it is the very first element following the opening body tag and will always appear at the top of the page. How can I go about accomplishing that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

囚你心 2025-01-23 15:49:39

从组件内部:

document.body.insertBefore(this, document.body.firstChild);
// or, for evergreen browsers, if you don't care about IE:
document.body.prepend(this);

从外部,如果您的元素已经在 DOM 中但需要移动:

document.body.insertBefore(document.querySelector('page-alert'), document.body.firstChild);
// or, for evergreen browsers, if you don't care about IE:
document.body.prepend(document.querySelector('page-alert'));

From inside your component:

document.body.insertBefore(this, document.body.firstChild);
// or, for evergreen browsers, if you don't care about IE:
document.body.prepend(this);

From the outside, if your element is already in the DOM but needs to be moved:

document.body.insertBefore(document.querySelector('page-alert'), document.body.firstChild);
// or, for evergreen browsers, if you don't care about IE:
document.body.prepend(document.querySelector('page-alert'));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文