uni-app鸿蒙上架必备技能:应用适配深色模式
此文将介绍 uni-app 如何适配深色模式,文章内容通俗易懂,非常适合新手小白上手,从此再也不用担心如何适配深色模式了。
- 示例项目仓库地址:gitee仓库地址
为什么要适配深色模式?
- 鸿蒙应用商店上架强制要求
- 提升用户体验
- 符合现代应用设计趋势
开发环境要求
- HBuilderX 4.76+
- 当前必须手动在
harmony-configs/libs目录增加UniAppRuntime.har
注意: UniAppRuntime.har 文件请在示例项目中复制
快速上手(三步搞定)
第一步:启用深色模式支持
在 manifest.json 中添加配置:
{
// 鸿蒙App
"app-harmony": {
"darkmode": true,
"themeLocation": "theme.json",
"safearea": {
"bottom": {
"offset": "none"
}
}
},
// iOS 和 安卓
"app-plus": {
"darkmode": true,
"themeLocation": "theme.json",
"safearea": {
"bottom": {
"offset": "none"
}
},
},
// Web
"h5": {
"darkmode": true,
"themeLocation": "theme.json"
},
// 微信小程序
"mp-weixin": {
"darkmode": true,
"themeLocation": "theme.json",
}
}
说明:darkmode: true 表示启用深色模式,themeLocation 指定主题配置文件位置。
第二步:创建主题配置文件
在项目根目录创建 theme.json,定义浅色和深色两套颜色:
{
"light": {
"navBgColor": "#ffffff",
"navTxtStyle": "black",
"bgColor": "#f5f5f5",
"tabBgColor": "#ffffff",
"tabFontColor": "#666666",
"tabSelectedColor": "#007aff",
"tabBorderStyle": "black"
},
"dark": {
"navBgColor": "#1a1a1a",
"navTxtStyle": "white",
"bgColor": "#000000",
"tabBgColor": "#1a1a1a",
"tabFontColor": "#999999",
"tabSelectedColor": "#0a84ff",
"tabBorderStyle": "white"
}
}
说明:
light:浅色模式下的颜色dark:深色模式下的颜色- 可以自定义任意颜色变量
- 此处的变量仅在
pages.json文件中使用
第三步:在 pages.json 中使用主题变量
使用 @变量名 的方式引用主题颜色:
{
"globalStyle": {
"navigationBarTextStyle": "@navTxtStyle",
"navigationBarTitleText": "深色模式示例",
"navigationBarBackgroundColor": "@navBgColor",
"backgroundColor": "@bgColor"
},
"tabBar": {
"color": "@tabFontColor",
"selectedColor": "@tabSelectedColor",
"backgroundColor": "@tabBgColor",
"borderStyle": "@tabBorderStyle",
"list": [...]
}
}
说明:系统会根据当前模式自动选择对应的颜色值。
页面样式适配
上面操作的3步骤仅适配了顶部导航和底部tabbar,接下来将介绍页面样式如何适配深色模式。
核心: 使用 CSS 变量 + 媒体查询覆盖 CSS 变量的值
第一步:项目根目录创建 theme.scss 文件:
:root,
page {
// 背景色
--page-bg: #f5f5f5;
--card-bg: #ffffff;
// 文字色
--text-primary: #333333;
--text-secondary: #666666;
// 主题色
--primary-color: #007aff;
// 边框色
--border-color: #f0f0f0;
}
// 深色模式
@media (prefers-color-scheme: dark) {
:root,
page {
// 背景色
--page-bg: #000000;
--card-bg: #1a1a1a;
// 文字色
--text-primary: #ffffff;
--text-secondary: #999999;
// 主题色
--primary-color: #0a84ff;
// 边框色
--border-color: #2a2a2a;
}
}
page {
background-color: var(--page-bg);
}
第二步:在 App.vue 中引入:
<style lang="scss">
@import "./theme.scss";
</style>
第三步:在页面中使用 CSS 变量:
<style lang="scss" scoped>
.container {
background-color: var(--page-bg);
}
.card {
background-color: var(--card-bg);
color: var(--text-primary);
}
.text {
color: var(--text-secondary);
}
</style>
常见问题
1. 如何测试深色模式?
- 鸿蒙设备:设置 → 显示与亮度 → 深色模式 → 全天开启
- iOS/Android:在系统设置中切换外观
- 谷歌浏览器:设置 → 外观 → 主题
- 微信小程序:跟随微信App的设置
2. 底部tabbar的图标怎么适配?
建议使用通用的黑白图标,或者在 theme.json 中定义不同的图标路径。
核心要点总结
- 在
manifest.json中启用darkmode: true - 创建
theme.json定义颜色变量 - 在
pages.json中使用@变量名引用 - 使用 CSS 变量 + 媒体查询适配页面样式
- 测试浅色和深色两种模式下的显示效果
1 个评论
要回复文章请先登录或注册
姜六六