vue实现手机横屏
Vue 实现手机横屏的方法
使用 CSS 媒体查询强制横屏
通过 CSS 的 @media 查询检测屏幕方向,并强制横屏显示。适用于简单的横屏需求。
@media screen and (orientation: portrait) {
html {
transform: rotate(90deg);
transform-origin: left top;
width: 100vh;
height: 100vw;
overflow-x: hidden;
position: absolute;
top: 100%;
left: 0;
}
}
监听屏幕方向变化
通过 JavaScript 监听 orientationchange 事件,动态调整页面布局或提示用户横屏。

mounted() {
window.addEventListener('orientationchange', this.handleOrientationChange);
this.handleOrientationChange(); // 初始检查
},
beforeDestroy() {
window.removeEventListener('orientationchange', this.handleOrientationChange);
},
methods: {
handleOrientationChange() {
const isLandscape = Math.abs(window.orientation) === 90;
if (!isLandscape) {
alert('请横屏以获得最佳体验');
}
}
}
使用 Fullscreen API 强制横屏
结合 Fullscreen API 和 CSS 旋转,实现更稳定的横屏效果。
methods: {
enterLandscape() {
const element = document.documentElement;
if (element.requestFullscreen) {
element.requestFullscreen().then(() => {
screen.orientation.lock('landscape').catch(err => {
console.error('锁定横屏失败:', err);
});
});
}
}
}
使用第三方库
引入如 screenfull 或 vue-screen-orientation 等库简化横屏实现。

安装 screenfull:
npm install screenfull
使用示例:
import screenfull from 'screenfull';
methods: {
toggleFullscreen() {
if (screenfull.isEnabled) {
screenfull.request().then(() => {
window.screen.orientation.lock('landscape');
});
}
}
}
注意事项
- 兼容性:
screen.orientation.lock可能不被所有浏览器支持,需测试目标平台。 - 用户提示:建议在无法强制横屏时提供友好的提示引导用户手动切换。
- 样式适配:横屏后需重新计算布局,避免内容溢出或错位。
以上方法可根据实际需求组合使用,优先考虑 CSS 方案,复杂场景可结合 JavaScript 和第三方库。






