这是 motion-carousel 元素的简单脚手架,样式被分离到一个模块中以便于阅读。 <motion-carousel>index.html 中使用,并填充了一组图片。

第一个任务是为轮播设置一些基本的 DOM 和样式。 你可能会注意到元素内部的图片没有显示出来。这是因为元素的 Shadow DOM 被显示了,而其中没有 slot 元素。查看文档 了解更多关于插槽如何工作的信息。

添加一个 slot

<div class="fit">
<slot></slot>
</div>

然后,元素内容就神奇地出现了。现在元素需要一些基本样式, 以便项目能够正确地适配其中。

打开 styles 模块并添加以下样式:

styles

Permalink to "styles"
:host {
display: inline-block;
overflow: hidden;
position: relative;
/* 默认值 */
width: 200px;
height: 200px;
border-radius: 4px;
background: gainsboro;
cursor: pointer;
}

.fit {
position: relative;
height: 100%;
width: 100%;
}

::slotted(*) {
box-sizing: border-box;
width: 100%;
height: 100%;
}

由于轮播负责显示选中的项目并管理其外观,最简单的方式是要求它具有明确的尺寸。 这样,你可以确保项目被包含在轮播内部。这是通过 overflow: hidden 来实现的。 项目被显式设置为 100% 的尺寸,使其适配在轮播内部。

注意 Shadow DOM 的 CSS 选择器::host 用于设置元素本身的样式, ::slotted(*) 用于设置所有被分发的子元素的样式。

:host 选择器中的属性实际上是元素的默认值,重要的是要记住用户可以 覆盖这些属性来定制外观。

在 Lit 文档中了解更多关于主题化样式设置以及 :host:slotted 选择器的信息。