场景:项目组新开发一个webapp 项目,嵌入到集团应用内,项目本身需要横向展示界面,所以需要 webapp 的方向始终保持在手机横向展示。
问题1:总是保持app界面以横屏显示。当手机是竖屏的时候,app界面旋转90度来保持横向显示,当手机是横屏的时候,app界面不需要旋转,保持和手机方向一致。
;(function() {
function setAppLandscape() {
const doc = document.documentElement || document.body
const app = document.getElementById('app')
const { clientWidth: width, clientHeight: height } = doc
if (width < height) {
app.style.width = `${height}px`
app.style.height = `${width}px`
app.style.left = `${-(height - width)/2}px`
app.style.top = `${(height - width)/2}px`
app.style.transform = 'rotate(90deg)'
app.style.transformOrigin = '50% 50%'
} else {
app.style.width = '100%'
app.style.height = '100%'
app.style.left = '0px'
app.style.top = '0px'
app.style.transform = 'none'
}
}
setAppLandscape()
window.addEventListener('resize', setAppLandscape(), false)
})()
问题2:适配移动端界面。
;(function() {
function fixRootFontSize() {
const doc = document.documentElement || document.body
const root = document.getElementByTagName('html')[0]
const { width } = doc.getBoundingClientRect()
// 借鉴淘宝移动端适配的思路,将设计稿分成10等份
const rem = width / 10
root.style.fontSize = rem + 'px'
}
})()
总结:把两者合在一起。
;(function() {
function flexible() {
const doc = document.documentElement || document.body
const root = document.getElementByTagName('html')[0]
const app = document.getElementById('app')
const { width, height } = doc.getBoundingClientRect()
// 借鉴淘宝移动端适配的思路,将设计稿分成10等份
let rem = width / 10
if (width < height) {
app.style.width = `${height}px`
app.style.height = `${width}px`
app.style.left = `${-(height - width)/2}px`
app.style.top = `${(height - width)/2}px`
app.style.transform = 'rotate(90deg)'
app.style.transformOrigin = '50% 50%'
rem = height / 10
} else {
app.style.width = '100%'
app.style.height = '100%'
app.style.left = '0px'
app.style.top = '0px'
app.style.transform = 'none'
}
root.style.fontSize = rem + 'px'
}
flexible()
window.addEventListener('resize', flexible(), false)
})()
最后:px转rem自动化。使用 postcss-px2rem 插件来自动将px转化为rem,其配置如下:
psotcss: {
plugins: {
require('postcss-px2rem')({
remUnit: 84.4,
propList: ['*'],
minPixelValue: 2
})
}
}
本人使用的设计稿尺寸是 iphone 12 的尺寸,884 * 390,故这里的 remUnit使用的是884 / 10 作为1rem对应的px。 大家实际使用时要以自己拿到的设计稿尺寸作为基准。