WeChat Mini Program adaptation tips
WeChat Mini Program Adaptation Techniques
In WeChat Mini Program development, adapting to different device screens is a common requirement. As a cross-platform framework, uni-app provides multiple adaptation solutions, and developers need to choose the appropriate method based on project characteristics.
Viewport Unit Adaptation
Using the rpx
unit is the recommended adaptation solution for WeChat Mini Programs. The rpx
unit adapts based on screen width, with a standard screen width of 750rpx.
// Example: Using rpx to define element dimensions
<view style="width: 750rpx; height: 200rpx; background-color: #f0f0f0;"></view>
Key considerations in actual development:
- Design drafts are typically based on a 750px width standard.
- 1px in the design draft = 1rpx.
- Font sizes should use both
px
andrpx
as a fallback solution.
/* Font size adaptation example */
.text {
font-size: 28rpx;
font-size: 14px; /* Compatibility solution */
}
Flex Layout Adaptation
Flex layout effectively addresses element arrangement issues across different screen sizes.
<!-- Example: Flex horizontal arrangement adaptation -->
<view class="container">
<view class="item">Item 1</view>
<view class="item">Item 2</view>
<view class="item">Item 3</view>
</view>
/* Corresponding styles */
.container {
display: flex;
flex-direction: row;
justify-content: space-around;
}
.item {
flex: 1;
text-align: center;
}
Conditional Compilation for Platform Differences
uni-app supports conditional compilation, allowing special handling for WeChat Mini Programs.
// Example: Platform conditional compilation
// #ifdef MP-WEIXIN
console.log('This code only executes in WeChat Mini Programs');
wx.showToast({
title: 'WeChat-exclusive notification'
});
// #endif
Safe Area Adaptation
For full-screen phones, consider the bottom safe area using env(safe-area-inset-bottom)
.
/* Safe area adaptation example */
.page {
padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
}
Image Adaptation Techniques
Image adaptation can use the following solutions:
- Use the
mode
property to control image display. - For network images, use CDN with size parameters.
- For local images, use multi-resolution image solutions.
<!-- Image adaptation example -->
<image
src="/static/logo.png"
mode="widthFix"
style="width: 100%;"
></image>
Dynamic Font Size Adjustment
For scenarios requiring dynamic font size adjustment:
// Calculate font size suitable for the current screen
function getFontSize(baseSize) {
const systemInfo = uni.getSystemInfoSync();
const scale = systemInfo.windowWidth / 375; // Based on a 375px design draft
return Math.round(baseSize * scale);
}
Dynamic Component Size Calculation
Complex layouts may require dynamic component size calculations:
// Example: Dynamic calculation of grid size
export default {
data() {
return {
gridSize: 0
}
},
mounted() {
this.calculateGridSize();
},
methods: {
calculateGridSize() {
const systemInfo = uni.getSystemInfoSync();
const screenWidth = systemInfo.windowWidth;
this.gridSize = (screenWidth - 40) / 3; // Divide into three equal parts after subtracting margins
}
}
}
Landscape and Portrait Adaptation
Handle device orientation changes by listening to events:
// Landscape and portrait adaptation example
onLoad() {
uni.onWindowResize((res) => {
console.log('Window size changed', res.size);
this.handleLayoutChange();
});
},
methods: {
handleLayoutChange() {
const systemInfo = uni.getSystemInfoSync();
if (systemInfo.windowWidth > systemInfo.windowHeight) {
// Landscape layout
} else {
// Portrait layout
}
}
}
High-Resolution Device Adaptation
For Retina and other high-resolution devices:
/* 2x image adaptation */
.icon {
width: 50rpx;
height: 50rpx;
background-image: url('/static/icon@2x.png');
background-size: 100% 100%;
}
/* Adapt to higher resolutions via media queries */
@media (-webkit-min-device-pixel-ratio: 3) {
.icon {
background-image: url('/static/icon@3x.png');
}
}
Custom Navigation Bar Adaptation
Custom navigation bars need to account for the status bar height:
// Get the required height for the navigation bar
const systemInfo = uni.getSystemInfoSync();
const statusBarHeight = systemInfo.statusBarHeight;
const menuButtonInfo = wx.getMenuButtonBoundingClientRect();
const navBarHeight = (menuButtonInfo.top - statusBarHeight) * 2 + menuButtonInfo.height;
Multilingual Layout Adaptation
Text length differences in different languages may cause layout issues:
/* Multilingual text container */
.text-container {
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
Theme Switching Adaptation
Dynamic styles are required for theme switching support:
// Dynamic theme example
data() {
return {
themeStyle: {
'--primary-color': '#007aff',
'--bg-color': '#ffffff'
}
}
},
methods: {
changeTheme(dark) {
if (dark) {
this.themeStyle = {
'--primary-color': '#0a84ff',
'--bg-color': '#1c1c1e'
};
} else {
this.themeStyle = {
'--primary-color': '#007aff',
'--bg-color': '#ffffff'
};
}
}
}
/* Using CSS variables */
.page {
background-color: var(--bg-color);
color: var(--primary-color);
}
Performance Optimization for Adaptation
Consider performance impacts during adaptation:
- Avoid frequent use of
calc()
. - Minimize unnecessary reflows and repaints.
- Cache complex calculation results.
// Example of caching calculation results
let cachedSize = null;
function getAdaptiveSize() {
if (!cachedSize) {
const systemInfo = uni.getSystemInfoSync();
cachedSize = systemInfo.windowWidth / 750 * 100;
}
return cachedSize;
}
Handling Device API Differences
Device API capabilities vary across devices:
// Safely call device APIs
function safeGetSystemInfo() {
return new Promise((resolve) => {
if (typeof uni.getSystemInfo === 'function') {
uni.getSystemInfo({
success: resolve,
fail: () => resolve(null)
});
} else {
resolve(null);
}
});
}
Complex Interaction Adaptation
For complex interaction scenarios, use CSS variables for dynamic control:
// Dynamic control of interactive elements
data() {
return {
interactiveStyle: {
'--scale-factor': 1,
'--translate-y': '0'
}
}
},
methods: {
handleTouchStart(e) {
this.interactiveStyle['--scale-factor'] = 0.95;
},
handleTouchEnd(e) {
this.interactiveStyle['--scale-factor'] = 1;
}
}
.interactive-element {
transform: scale(var(--scale-factor)) translateY(var(--translate-y));
transition: all 0.2s ease;
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:条件编译实现多端适配
下一篇:安卓与 iOS 的兼容性问题