可以通过旋转的角度来判断
1. window.onresize 只会在手机开启自动旋转后才会触发。
2. 通过 window.orientation 来判断是否旋转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="./js/zepto.min.js"></script>
<title>Document</title>
</head>
<body>
<style>
.test {
position: absolute;
left: 0;
top: 0;
background: black;
color: #fff;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
let index = 0
console.log(width)
console.log(height)
$(function () {
if (width < height) {
$('.test').css({
width: height + 'px',
height: width + 'px',
top: (height - width) / 2 + 'px',
left: 0 - (height - width) / 2 + 'px',
transform: 'rotate(90deg)',
})
} else { // 页面一开始就是横屏的情况(自动旋转)
$('.test').css({
width: width + 'px',
height: height + 'px',
top: 0,
left: 0,
transform: 'rotate(0deg)',
})
}
})
function setWidth() {
index++
const width = document.documentElement.clientWidth;
const height = document.documentElement.clientHeight;
console.log(width)
console.log(height)
if (window.orientation === 0 || window.orientation === 180) { // 竖屏
$('.test').css({
width: height + 'px',
height: width + 'px',
top: (height - width) / 2 + 'px',
left: 0 - (height - width) / 2 + 'px',
transform: 'rotate(90deg)',
})
$('#vsztms', window.parent.document).css({ // 这个是因为我的页面使用
iframe嵌入进来的,横屏的时候没有自适应,
所有我这边更改了父级iframe的宽高
'height': width,
'width': height
});
} else {
if (index === 1) {
return
}
$('.test').css({
width: width + 'px',
height: height + 'px',
top: 0,
left: 0,
transform: 'rotate(0deg)',
})
$('#vsztms', window.parent.document).css({
'height': width,
'width': height
});
}
}
$(function () {
setWidth()
window.onresize = setWidth
})
</script>
<div class="test" id="test">
安河桥下
</div>
</body>
</html>