背景
纯css
@media screen and (orientation: portrait) {
.main {
-webkit-transform:rotate(-90deg);
-moz-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
width: 100vh;
height: 100vh;
/*去掉overflow 微信显示正常,但是浏览器有问题,竖屏时强制横屏缩小*/
overflow: hidden;
}
}
@media screen and (orientation: landscape) {
.main {
-webkit-transform:rotate(0);
-moz-transform: rotate(0);
-ms-transform: rotate(0);
transform: rotate(0)
}
}
width: 100vh;
height: 100vh;
js计算宽高、对齐、旋转
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
if( width < height ){
$print = $('#print');
$print.width(height);
$print.height(width);
$print.css('top', (height-width)/2);
$print.css('left', 0-(height-width)/2 );
$print.css('transform' , 'rotate(90deg)');
$print.css('transform-origin' , '50% 50%');
}
最终方案
var evt = "onorientationchange" in window ? "orientationchange" : "resize";
window.addEventListener(evt, function() {
console.log(evt);
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
$print = $('#print');
if( width > height ){
$print.width(width);
$print.height(height);
$print.css('top', 0 );
$print.css('left', 0 );
$print.css('transform' , 'none');
$print.css('transform-origin' , '50% 50%');
}
else{
$print.width(height);
$print.height(width);
$print.css('top', (height-width)/2 );
$print.css('left', 0-(height-width)/2 );
$print.css('transform' , 'rotate(90deg)');
$print.css('transform-origin' , '50% 50%');
}
}, false);
完整代码
/**
* 横竖屏
* @param {Object}
*/
function changeOrientation($print) {
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
if(width < height) {
$print.width(height);
$print.height(width);
$print.css('top', (height - width) / 2 );
$print.css('left', 0 - (height - width) / 2 );
$print.css('transform', 'rotate(90deg)');
$print.css('transform-origin', '50% 50%');
}
var evt = "onorientationchange" in window ? "orientationchange" : "resize";
window.addEventListener(evt, function() {
setTimeout(function() {
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
// 刷新城市的宽度
initCityWidth();
// 初始化每个气泡和自行车碰撞的距离
cityCrashDistanceArr = initCityCrashDistance();
if( width > height ){
$print.width(width);
$print.height(height);
$print.css('top', 0 );
$print.css('left', 0 );
$print.css('transform' , 'none');
$print.css('transform-origin' , '50% 50%');
}
else {
$print.width(height);
$print.height(width);
$print.css('top', (height-width)/2 );
$print.css('left', 0-(height-width)/2 );
$print.css('transform' , 'rotate(90deg)');
$print.css('transform-origin' , '50% 50%');
}
}, 300);
}, false);
}
总结
该方案只适合页面宽高占一屏,不适合可以滚动的方案,用orientationchange和resize监听横竖屏切换会有延迟的问题,具体解决延迟的方案见我的另外一篇文章
js实现手机横竖屏事件