您现在的位置是:亿华云 > 域名

Web Components 系列之实现 MyCard 的基本布局

亿华云2025-10-08 23:20:23【域名】3人已围观

简介前言前面针对 Web Components 学习了一些基本的理论知识,我们了解到的概念有:Custom ElementsShadow DOMTemplatesSlots以及和这些概念相关的子知识点。理

前言

前面针对 Web Components 学习了一些基本的实现理论知识,我们了解到的本布概念有:

Custom ElementsShadow DOMTemplatesSlots

以及和这些概念相关的子知识点。

理论知识基本上够用了,实现从现在开始我们需要将理论运用到实践中,本布让理论为实践服务。实现今天,本布我们就使用 Web Components 的实现相关知识来实现 MyCard 的免费信息发布网制作,原型呢就以我们人人都有的本布身份证做参照吧。

最终实现的实现基本布局效果如下:

使用 Templates 布局

这里我们使用 HTML 模板将布局先构建出来,代码如下:

* {

box-sizing: border-box;

}

:host {

display: inline-block;

width: 400px;

height: 240px;

border: 1px solid black;

border-radius: 10px;

box-shadow: -2px -2px 5px 0px #7a8489;

}

.container {

display: flex;

flex-direction: column;

padding: 10px;

height: 100%;

}

.card-body {

flex: 1;

display: flex;

}

.card-footer {

padding: 10px 0;

}

.main-info {

flex: 2;

}

.photo {

flex: 1;

display: flex;

align-items: center;

}

.photo img{

width: 100%;

}

.info-row {

display: flex;

padding-top: 15px;

}

.info-column {

display: flex;

align-items: center;

}

.info-title {

padding: 0 10px;

color: #0e5bd3;

font-size: 12px;

word-break: keep-all;

}

.info-content {

letter-spacing: 2px;

}

姓名 编程三昧 性别 男 民族 汉 出生 2022 年 12 月 12 日 住址 xx省xx市xx区xx街道xx小区xx楼xx单元xx楼xx室

公民身份号码 12345678901234567X</template>

创建自定义元素

使用我们前面学习过的本布方法,创建一个基本的实现自定义元素 my-card,在自定义组件中引入 Templates 布局,云服务器提供商本布代码如下:

class MyCard extends HTMLElement {

constructor () {

super();

this.shadow = this.attachShadow({ mode: "open"});

let tempEle = document.getElementById("card_layout");

this.shadow.appendChild(tempEle.content);

}

}

customElements.define("my-card",实现 MyCard);

使用自定义元素

在 HTML 的 body 中引入 my-card 标签:

<my-card></my-card>

总结

最终实现的效果如文章开头所示。

在这篇文章中,本布我们只使用 Custom Elements 和 Templates 实现了基本布局和样式,实现实用价值基本为零。

在后续中,会加入 Slots 让自定义元素实现可复用的效果。

~

高防服务器

很赞哦!(59)