我正在使用 Angular 14 中的应用程序。如何阻止方向更改?我的意思是,我希望屏幕始终水平显示。
我尝试过这样做,但它并没有占据屏幕的整个宽度,而是保持垂直的宽度。因此内容保留在屏幕中间。我也尝试添加
width: 100vw
但它不起作用。
@media only screen and (orientation:portrait) {
body {
height: 100vw;
transform: rotate(90deg);
}
}
在使用 JS 的情况下,
lock()
方法已被弃用。
https://developer.mozilla.org/en-US/docs/Web/API/Screen/lockOrientation https://developer.mozilla.org/en-US/docs/Web/API/ScreenOrientation/lock
我找到了三种查看设备方向的方法
一种方法是使用原生js实现全屏视图
// (A1) GO INTO FULL SCREEN FIRST
let de = document.documentElement;
if (de.requestFullscreen) { de.requestFullscreen(); }
else if (de.mozRequestFullScreen) { de.mozRequestFullScreen(); }
else if (de.webkitRequestFullscreen) { de.webkitRequestFullscreen(); }
else if (de.msRequestFullscreen) { de.msRequestFullscreen(); }
// (A2) THEN LOCK ORIENTATION
screen.orientation.lock('landscape');
第二种方法是使用CSS
@media only screen and (orientation:portrait) {
body {
height: 100vw;
transform: rotate(90deg);
}
}
第三种方法是提醒用户旋转设备
<!-- (A) THIS WILL SHOW ON THE WRONG ORIENTATION -->
<div id="turn">
Please rotate your device!
</div>
<!-- (B) CONTENTS AS USUAL -->
<div id="container">
Main contents here.
</div>
/* (A) WRONG ORIENTATION - SHOW MESSAGE HIDE CONTENT */
@media only screen and (orientation:landscape) {
#turn { display:block; }
#container { display:none; }
}
/* (B) CORRECT ORIENTATION - SHOW CONTENT HIDE MESSAGE */
@media only screen and (orientation:portrait) {
#turn { display:none; }
#container { display:block; }
}
要将方向锁定为水平,您可以使用 CSS 以及 Angular 的特定于平台的 API。
CSS 横向
@media only screen and (orientation: portrait) {
body {
transform: rotate(90deg);
transform-origin: left top;
width: 100vh;
height: 100vw;
overflow-x: hidden;
position: fixed;
top: 0;
left: 0;
}
}
方向锁定的角度组件
import { Platform } from '@angular/cdk/platform';
import { Component, HostListener } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private platform: Platform) {
if (this.platform.ANDROID || this.platform.IOS) {
this.lockOrientation();
}
}
lockOrientation() {
if (screen.orientation?.lock) {
screen.orientation.lock('landscape');
}
}
@HostListener('window:orientationchange', ['$event'])
onOrientationChange(event: Event) {
event.preventDefault();
}
}