Terrarium 项目是一个交互式 Web 应用程序,允许用户通过拖放植物图像来创建和自定义虚拟的植物生态瓶。本文档介绍了 Terrarium 项目的系统架构、组件和实现细节,重点介绍了 HTML、CSS 和 JavaScript 如何协同工作以创建引人入胜的交互式 Web 体验。
Terrarium 项目通过创建一个简单的拖放界面来演示基本的 Web 开发概念。该系统包含三个主要组件
来源:3-terrarium/1-intro-to-html/README.md10-21 3-terrarium/2-intro-to-css/README.md10-17 3-terrarium/3-intro-to-DOM-and-closures/README.md10-19
HTML 组件创建了植物生态瓶界面的骨架结构,定义了元素的布局和定位。
植物生态瓶界面包含:
来源:3-terrarium/1-intro-to-html/README.md111-169 3-terrarium/1-intro-to-html/README.md196-214
每株植物都结构为一个嵌套的 div 集合,具有特定的类名和 ID,以便于样式设置和 JavaScript 交互。
此结构为所有 14 株植物重复使用,ID 从 plant1 到 plant14 依次排列。
来源:3-terrarium/1-intro-to-html/README.md118-139 3-terrarium/1-intro-to-html/README.md140-162
CSS 组件为植物生态瓶界面提供视觉样式,创建了玻璃容器的外观并定位了植物。
| 元素 | 目的 | 关键 CSS 属性 |
|---|---|---|
.container | 容纳两侧的植物元素 | position: absolute, width: 15% |
.plant-holder | 定位单个植物 | position: relative, height: 13% |
.plant | 样式化植物图像 | position: absolute, max-width: 150%, z-index: 2 |
.jar-walls | 创建植物生态瓶的玻璃效果 | height: 80%, width: 60%, border-radius: 1rem, opacity: 0.5 |
.dirt | 创建土壤外观 | width: 60%, height: 5%, background: #3a241d |
来源:3-terrarium/2-intro-to-css/README.md102-126 3-terrarium/2-intro-to-css/README.md151-163 3-terrarium/2-intro-to-css/README.md193-242
该植物生态瓶结合使用了相对定位和绝对定位来创建布局。
来源:3-terrarium/2-intro-to-css/README.md177-188
JavaScript 组件使用 DOM 操作和闭包来实现拖放功能。
来源:3-terrarium/3-intro-to-DOM-and-closures/README.md98-107 3-terrarium/3-intro-to-DOM-and-closures/README.md124-130 3-terrarium/3-intro-to-DOM-and-closures/README.md159-167 3-terrarium/3-intro-to-DOM-and-closures/README.md182-186
JavaScript 首先从 DOM 中识别和选择所有植物元素。
每个植物元素都会传递给 dragElement 函数,该函数启用拖动功能。
来源:3-terrarium/3-intro-to-DOM-and-closures/README.md48-64
该项目使用 JavaScript 闭包模式,其中外部函数(dragElement)封装了三个内部函数:
pointerDrag:在点击植物时初始化拖动。elementDrag:在拖动过程中更新植物的位置。stopElementDrag:在释放指针时终止拖动。此模式允许内部函数访问和修改外部函数作用域中声明的位置变量。
来源:3-terrarium/3-intro-to-DOM-and-closures/README.md99-107 3-terrarium/3-intro-to-DOM-and-closures/README.md73-94
拖动过程中,元素位置的计算步骤如下:
pos3 和 pos4)。pos1 和 pos2)。top 和 left 属性。来源:3-terrarium/3-intro-to-DOM-and-closures/README.md159-167
下图说明了使用植物生态瓶时的用户交互流程。
来源: 3-terrarium/3-intro-to-DOM-and-closures/README.md117-147 3-terrarium/3-intro-to-DOM-and-closures/README.md150-188
该项目使用指针事件 API,而不是鼠标事件,以提高跨平台兼容性。使用的关键事件包括:
onpointerdown:用户点击/触摸植物时触发onpointermove:指针移动时持续触发onpointerup:用户释放指针时触发此方法允许该温室在触摸设备和传统鼠标界面上都能正常工作。
来源: 3-terrarium/3-intro-to-DOM-and-closures/README.md111-114
该系统使用多种 CSS 定位技术
| 定位类型 | 用于 | 目的 |
|---|---|---|
absolute | 侧边容器、温室元素 | 将元素固定到特定位置 |
relative | 植物支架 | 为植物创建定位上下文 |
z-index | 植物、温室元素 | 控制元素的层叠顺序 |
这种组合可以创建具有可拖动元素的视觉分层界面。
来源:3-terrarium/2-intro-to-css/README.md177-188
温室项目展示了几个基本的 Web 开发概念:
该项目通过实践应用,是这些概念的绝佳入门。
来源: 3-terrarium/1-intro-to-html/README.md182-195 3-terrarium/2-intro-to-css/README.md177-188 3-terrarium/3-intro-to-DOM-and-closures/README.md72-91