需求:在微信端打开H5,在竖屏状态强行横屏展示,横屏状态则正常展示。
一、postcss配置
module.exports ={
plugins: [
"autoprefixer",
["postcss-px-to-viewport", {
// viewportWidth: 393, //视口的宽度,对应的时设计稿的宽度/2,一般为750
// viewportHeight: 852, //视口的高度,对应的是设计稿的高度(也可以不配置)
landscapeWidth:724,
landscapeHeight:355,
// landscape: true,
landscape: true, // 是否处理横屏情况
landscapeUnit:'vw', // (String) 横屏时使用的单位
viewportWidth: 375, //视口的宽度,对应的时设计稿的宽度/2,一般为750
// viewportHeight: 393, //视口的高度,对应的是设计稿的高度(也可以不配置)
unitPrecision: 2, //指定‘px’转换为视口单位值的小数位数(很多时候无法整除)
viewportUnit: "vw", //指定需要转换成的视口单位,建议使用vw
selectorBlankList: ["ignore", "tab-bar",""], //指定不需要转换的类
minPixelValue: 1, //小于或等于‘1px’不转换为视口单位
mediaQuery: false, //允许在媒体查询中转换为‘px’
exclude: [/total\.h5\.css$/, /CellToast\.css$/], //不需要转化的组件文件名正则,必须是正则表达式
}],
]
}
注意:配置landscapeWidth和landscapeHeight,否则真实横屏样式会出现错乱。postcss版本大于8配置这两个属性会出错,建议固定7.0.32版本
二、CSS
//最外层
.root {
transform: rotate(90deg);//顺时针旋转90度
transform-origin: 0% 100%;
top: -90vw;
position: absolute;
height: 100vw; //宽高单位互换
width: 100vh;
}
三、js
const App = (props) => {
useEffect(() => {
resize()
window.addEventListener('orientationchange', resize);//监听旋转方向
}, [])
function resize() {
let root = document.querySelector(".root")
if (window.orientation == 180 || window.orientation == 0) {
// alert("竖屏状态!")
root.setAttribute("style", ' transform: rotate(90deg);transform-origin: 0% 100%;top: -100vw;position: absolute;height: 100vw;width: 100vh')
};
if (window.orientation == 90 || window.orientation == -90) {
// alert("横屏状态!")
root.setAttribute("style", ' transform: unset;transform-origin:unset;top: 0;left:0;position: absolute;height: 100%;width: 100%')
}
}
return (
<div className="root">
<h1>网页搭建案例展示</h1>
<h2>案例一:图片展</h2>
<h3>沪ICP备xxxxxxx号</h3>
</div>
);
}