本系列教程适合鸿蒙 HarmonyOS 初学者,为那些熟悉用 HTML 与 CSS 语法的 Web 前端开发者准备的。
本系列教程会将 HTML/CSS 代码片段替换为等价的 HarmonyOS/ArkUI 代码。
在Web开发中,我们使用CSS来控制元素的布局和样式。而在HarmonyOS的ArkUI中,我们使用声明式UI和链式API来实现相同的效果。本文将对比两种框架在布局方面的异同。
在Web开发中,CSS盒子模型包含内容(content)、内边距(padding)、边框(border)和外边距(margin)。
在ArkUI中,这些概念依然存在,只是写法有所不同,容易上手。
HTML/CSS代码:
<div class="box">
盒子模型
</div>
<style>
.box {
box-sizing: border-box;
/* 内容 */
width: 150px;
height: 100px;
/* 内边距 */
padding: 10px;
/* 边框 */
border: 10px solid pink;
/* 底部外边距 */
margin-bottom: 10px;
}
</style>
ArkUI代码:
Text('盒子模型')
.width(150)
.height(100)
.padding(10)
.border({ width: 10, style: BorderStyle.Solid, color: Color.Pink })
.margin({ bottom: 10 })
在Web开发中,我们使用 background-color
和 color
属性来设置背景色和文字颜色。
在ArkUI中,我们使用 backgroundColor
和 fontColor
方法。
HTML/CSS代码:
<div class="box">
背景色、文字色
</div>
<style>
.box {
/* 背景色 */
background-color: #36d;
/* 文字色 */
color: #fff;
}
</style>
ArkUI代码:
Text('背景色、文字色')
.backgroundColor('#36d')
.fontColor('#fff')
在Web开发中,我们使用 display: flex
配合 justify-content
和 align-items
实现内容居中。
在ArkUI中,我们可以使用 Column
或 Row
组件配合 justifyContent
和 alignItems
属性。
HTML/CSS代码:
<div class="box">
内容居中
</div>
<style>
.box {
display: flex;
justify-content: center;
align-items: center;
}
</style>
ArkUI代码:
Column() {
Text('内容居中')
}
.backgroundColor('#36D')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.width(150)
.height(100)
.padding(10)
在Web开发中,我们使用border-radius
属性来设置圆角。
在ArkUI中,我们使用borderRadius
方法。
HTML/CSS代码:
<div class="box">
圆角
</div>
<style>
.box {
border-radius: 10px;
}
</style>
ArkUI代码:
Text('圆角')
.width(150)
.height(100)
.backgroundColor('#36D')
.borderRadius(10)
在Web开发中,我们使用box-shadow
属性来设置阴影效果。
在ArkUI中,我们使用shadow
方法。
HTML/CSS代码:
<div class="box">
阴影
</div>
<style>
.box {
box-shadow: 0 6px 50px rgba(0, 0, 0, 0.5);
}
</style>
ArkUI代码:
Text('阴影')
.width(150)
.height(100)
.backgroundColor('#F5F5F5')
.shadow({
offsetX: 0,
offsetY: 6,
radius: 50,
color: 'rgba(0, 0, 0, 0.5)',
})
在Web开发中,我们使用<div>
作为通用容器。
在ArkUI中,我们主要使用Column
和Row
组件,注意 alignItems
需区分轴向。
HTML/CSS代码:
<div class="column">
<!-- 垂直方向布局 -->
</div>
<div class="row">
<!-- 水平方向布局 -->
</div>
<style>
.column {
display: flex;
flex-direction: column;
align-items: center;
}
.row {
display: flex;
flex-direction: row;
align-items: center;
}
</style>
ArkUI代码:
Column() {
// 垂直方向布局,交叉轴水平居中
}
.alignItems(HorizontalAlign.Center)
Row() {
// 水平方向布局,交叉轴垂直居中
}
.alignItems(VerticalAlign.Center)
<div>
等标签,配合CSS实现布局Column
、Row
等组件,配合样式属性布局作为Web开发者,迁移到 HarmonyOS 开发需要适应新的布局和样式设置方式。概念其实非常相似,通过理解这些差异,并掌握ArkUI的组件化开发方式,Web开发者可以快速上手HarmonyOS开发。
希望这篇 HarmonyOS 教程对你有所帮助,期待您的 👍点赞、💬评论、🌟收藏 支持。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。