开发h5时时常会有横屏观看或竖屏观看的需求,根据情况进行调整
css3:
@media screen and (orientation: portrait) {
/*竖屏 css*/
}
@media screen and (orientation: landscape) {
/*横屏 css*/
}
js:
// 转屏时触发
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
if (window.orientation === 180 || window.orientation === 0) {
// 竖屏状态!
App.show = 0;
location.reload();
}
if (window.orientation === 90 || window.orientation === -90 ){
// 横屏状态!
App.show = 1;
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
if( width < height ){
console.log(width + " " + height);
$print = $('#app');
$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%');
}
location.reload();
}
}, false);
function orient() {
if (window.orientation == 0 || window.orientation == 180) {
// alert("竖屏 ");
App.show = 0;
//可针对横竖屏改变用js动态改变css样式
return false;
}
else if (window.orientation == 90 || window.orientation == -90) {
// alert("横屏 ");
var width = document.documentElement.clientWidth;
var height = document.documentElement.clientHeight;
console.log(width,height)
$print = $('#app');
$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%');
return false;
}
}
orient();