uniapp跨端适配方案
uniapp通过条件编译和响应式布局实现跨端适配,支持iOS、Android、H5及小程序等多端应用。以下是核心实现方法:
1.条件编译处理平台差异
通过process.env.UNI_PLATFORM
判断当前运行平台,针对不同平台编写差异化代码:
// #ifdef H5
console.log('仅在H5平台执行');
// #endif// #ifdef MP-WEIXIN
console.log('仅在微信小程序执行');
// #endif
2.响应式单位rpx与upx
使用rpx
(推荐)或upx
作为样式单位,uniapp会自动转换为各端适配的像素值:
.container {width: 750rpx; /* 满屏宽度 */padding: 20rpx;font-size: 28rpx;
}
3.动态样式处理
通过JS计算动态尺寸,结合uni.getSystemInfoSync()
获取设备信息:
const systemInfo = uni.getSystemInfoSync();
const windowWidth = systemInfo.windowWidth;// 计算元素宽度(示例:屏幕宽度的一半)
const elementWidth = windowWidth / 2 + 'px';
4.组件适配方案
使用match-media
组件实现媒体查询:
<match-media :min-width="375"><view>仅当屏幕宽度≥375px时显示</view>
</match-media>
4.图片多倍图适配
通过@2x
、@3x
后缀自动匹配高分辨率设备:
assets/├── logo.png├── logo@2x.png├── logo@3x.png
5.代码中引用基础图即可:
<image src="/static/logo.png"></image>
6.安全区域适配(iOS)
使用safe-area-inset-*
CSS变量处理iPhone刘海屏:
.page {padding-bottom: constant(safe-area-inset-bottom);padding-bottom: env(safe-area-inset-bottom);
}
7.完整示例代码
// 页面逻辑
export default {data() {return {statusBarHeight: 0}},onLoad() {const { statusBarHeight } = uni.getSystemInfoSync();this.statusBarHeight = statusBarHeight;}
}
<!-- 视图模板 -->
<template><view class="container"><!-- 状态栏占位 --><view :style="{ height: statusBarHeight + 'px' }"></view><!-- 条件编译内容 --><!-- #ifdef MP-WEIXIN --><button open-type="share">微信分享</button><!-- #endif --><!-- 响应式布局 --><view class="box"></view></view>
</template><style>
.container {padding: 20rpx;
}
.box {width: 80%;height: 200rpx;margin: 0 auto;background-color: #f0f0f0;
}
</style>
通过以上方法组合使用,可有效解决90%以上的跨端适配问题。实际开发中建议结合uni-ui
组件库,其内置多端适配逻辑可进一步降低开发成本。