移动端横屏
整体演示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 竖屏样式 */
@media all and (orientation: portrait) {
body div {
width: 200px;
height: 500px;
background-color: pink;
}
}
/* 横屏样式 */
@media all and (orientation: landscape) {
body div {
width: 500px;
height: 200px;
background-color: orangered;
}
}
</style>
</head>
<body>
<div >这个是大屏幕</div>
</body>
</html>
<script>
console.log('window:',window.orientation);
console.log('window:',window.orientationchange);
window.addEventListener("onorientationchange"in window ? "orientationchange": "resize", function() {
//判断window.orientation === 180||===0代表竖屏
if (window.orientation === 180 ||window.orientation=== 0){
console.log('竖屏状态!');
//竖屏情况下删除横屏样式
document.body.classList.remove("landscape");
};
//判断window.orientation === 90||===-90代表横屏
if (window.orientation === 90 ||window.orientation=== -90){
console.log('横屏状态!');
//竖屏情况下添加横屏样式
document.body.classList.add("landscape");
}
}, false);
// window.addEventListener("orientationchange", function () {
// if (window.orientation === 90 || window.orientation === -90) {
// console.log('横屏状态!');
// document.body.classList.add("landscape");
// } else {
// console.log('竖屏状态!');
// document.body.classList.remove("landscape");
// }
// });
</script>
---------------------------------------------------------------------------------------------------------------------------
可以使用JavaScript的`window.orientation`属性来判断当前屏幕的方向,其中0表示竖屏,90表示向左横屏,-90表示向右横屏。根据不同的方向,可以动态地修改CSS样式,以实现不同的布局效果。具体实现步骤如下:
1. 在CSS中定义针对横屏的样式,例如:
```
@media screen and (orientation: landscape) {
/* 横屏样式 */
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
}
```
2. 在JavaScript中监听`window.orientation`属性的变化,根据不同的值来添加或移除对应的CSS类,例如:
```
window.addEventListener("orientationchange", function() {
if (window.orientation === 90 || window.orientation === -90) {
document.body.classList.add("landscape");
} else {
document.body.classList.remove("landscape");
}
});
```
在以上代码中,当屏幕为横屏时,会给`<body>`元素添加`landscape`类,从而触发CSS中定义的横屏样式。当屏幕为竖屏时,则会移除该类,恢复默认样式。
需要注意的是,由于不同浏览器对`orientationchange`事件的支持可能不同,因此建议在事件处理函数中加入对`resize`事件的监听,以便在浏览器窗口大小发生变化时也能正确地更新样式。