guoyu/fronted_uniapp/utils/responsive.js
2025-12-03 18:58:36 +08:00

127 lines
2.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 响应式工具函数
* 用于检测设备类型、屏幕尺寸和横竖屏
*/
// 获取系统信息
function getSystemInfo() {
try {
return uni.getSystemInfoSync()
} catch (e) {
console.error('获取系统信息失败:', e)
return {
windowWidth: 375,
windowHeight: 667,
screenWidth: 375,
screenHeight: 667,
pixelRatio: 2
}
}
}
/**
* 判断是否为平板设备
* 通常平板宽度 >= 768px (在rpx中约为 1536rpx)
*/
export function isTablet() {
const systemInfo = getSystemInfo()
const windowWidth = systemInfo.windowWidth || systemInfo.screenWidth || 375
// 在H5环境下windowWidth是px单位
// 在UniApp中通常以rpx为基准750rpx = 屏幕宽度
// 平板判断:宽度 >= 768px (约等于 1536rpx / 2 = 768px)
return windowWidth >= 768
}
/**
* 判断是否为手机设备
*/
export function isMobile() {
return !isTablet()
}
/**
* 获取设备类型
* @returns {'mobile' | 'tablet'}
*/
export function getDeviceType() {
return isTablet() ? 'tablet' : 'mobile'
}
/**
* 是否横屏
*/
export function isLandscape() {
const systemInfo = getSystemInfo()
const width = systemInfo.windowWidth || systemInfo.screenWidth || 375
const height = systemInfo.windowHeight || systemInfo.screenHeight || 667
return width > height
}
/**
* 是否竖屏
*/
export function isPortrait() {
return !isLandscape()
}
/**
* 获取屏幕宽度px
*/
export function getScreenWidth() {
const systemInfo = getSystemInfo()
return systemInfo.windowWidth || systemInfo.screenWidth || 375
}
/**
* 获取屏幕高度px
*/
export function getScreenHeight() {
const systemInfo = getSystemInfo()
return systemInfo.windowHeight || systemInfo.screenHeight || 667
}
/**
* 响应式混入
* 可以在组件中使用
* this.isTablet, this.isMobile, this.deviceType
* this.isLandscape, this.isPortrait
*/
export const responsiveMixin = {
data() {
return {
deviceType: 'mobile',
screenWidth: 375,
screenHeight: 667,
isLandscape: false,
isPortrait: true
}
},
computed: {
isTablet() {
return this.deviceType === 'tablet'
},
isMobile() {
return this.deviceType === 'mobile'
}
},
onLoad() {
this.updateDeviceInfo()
},
onShow() {
this.updateDeviceInfo()
},
onResize() {
this.updateDeviceInfo()
},
methods: {
updateDeviceInfo() {
this.deviceType = getDeviceType()
this.screenWidth = getScreenWidth()
this.screenHeight = getScreenHeight()
this.isLandscape = isLandscape()
this.isPortrait = !this.isLandscape
}
}
}