Files
lgp-wx-plus/utils/device.js
2026-08-20 19:15:41 +08:00

84 lines
2.1 KiB
JavaScript
Raw 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.
/**
* 运行环境:区分手机微信与 PC 微信Windows / Mac
* 大屏适配只认官方 platform开发者工具手机预览不要走 PC 布局。
*/
export const PC_PAGE_MAX_WIDTH = 1200
const PC_PLATFORMS = { windows: true, mac: true }
export function isPcWeixin() {
try {
const sys = uni.getSystemInfoSync() || {}
const platform = String(sys.platform || '').toLowerCase()
return !!PC_PLATFORMS[platform]
} catch (e) {
return false
}
}
export function getWindowWidth() {
try {
const sys = uni.getSystemInfoSync() || {}
return Number(sys.windowWidth) || 375
} catch (e) {
return 375
}
}
/**
* 宽屏商品列数:卡片跟着窗口变窄、一行变多。
* 手机仍双列iPad / PC 中窗起加列,避免 rpx 把两列撑得过大。
*/
export function goodsColsByWidth(width) {
const w = Number(width) || 375
if (w >= 1200) return 5
if (w >= 900) return 4
if (w >= 600) return 3
return 2
}
/**
* 首页分类宫格列数:格子比商品卡更小,更早加列。
* mosaic / featured 这种非对称布局不要用这个函数去覆盖。
*/
export function catColsByWidth(width) {
const w = Number(width) || 375
if (w >= 1100) return 6
if (w >= 800) return 5
if (w >= 480) return 4
return 3
}
const widthListeners = []
let resizeBound = false
function emitWindowWidth(res) {
const size = (res && res.size) || {}
const width = Number(size.windowWidth) || getWindowWidth()
widthListeners.forEach((fn) => {
try {
fn(width)
} catch (e) {
// 单个页面抛错不影响其它订阅
}
})
}
/**
* 订阅窗口宽度。PC 拉伸窗口时通知页面改列数。
* 返回取消订阅函数,页面销毁时必须调用。
*/
export function watchWindowWidth(fn) {
if (typeof fn !== 'function') return function noop() {}
widthListeners.push(fn)
if (!resizeBound && typeof uni.onWindowResize === 'function') {
uni.onWindowResize(emitWindowWidth)
resizeBound = true
}
return function unwatch() {
const idx = widthListeners.indexOf(fn)
if (idx >= 0) widthListeners.splice(idx, 1)
}
}