モバイル端末で水平および垂直画面のビューポートの検出を実現するためのいくつかの方法

ビューポートのサイズと、それが縦画面か横画面かを検出する際に問題が発生することがあります.それを正しく検出するには? 早速、料理を直接サーブしましょう。

異なるビューポートを取得する方法

// 获取视觉视口大小(包括垂直滚动条)
let iw = window.innerWidth,
 ih = window.innerHeight;
console.log(iw, ih);

// 获取视觉视口大小(内容区域大小,包括侧边栏、窗口镶边和调整窗口大小的边框)
let ow = window.outerWidth,
 oh = window.outerHeight;
console.log(ow, oh);

// 获取屏幕理想视口大小,固定值(屏幕分辨率大小)
let sw = window.screen.width,
 sh = window.screen.height;
console.log(sw, sh);

// 获取浏览器可用窗口的大小(包括内边距、但不包括垂直滚动条、边框和外边距)
let aw = window.screen.availWidth,
 ah = window.screen.availHeight;
console.log(aw, ah);

// 包括内边距、滚动条、边框和外边距
let dow = document.documentElement.offsetWidth,
 doh = document.documentElement.offsetHeight;
console.log(dow, doh);

// 在不使用滚动条的情况下适合视口中的所有内容所需的最小宽度和高度
let dsW = document.documentElement.scrollWidth,
 dsH = document.documentElement.scrollHeight;
console.log(dsW, dsH);

// 包含元素的内边距,但不包括边框、外边距或者垂直滚动条
let cw = document.documentElement.clientWidth,
 ch = document.documentElement.clientHeight;
console.log(cw, ch);

jsは横画面と縦画面を検出します

// window.orientation:获取屏幕旋转方向
window.addEventListener('resize', () => {
 // 正常方向或屏幕旋转180度
 if (window.orientation === 180 || window.orientation === 0) {
  console.log('竖屏')
 }

 // 屏幕顺时钟旋转90度或屏幕逆时针旋转90度
 if (window.orientation === 90 || window.orientation === -90) {
  console.log('横屏')
 }
});

横画面と縦画面のCSS検出

@media screen and (orientation:portrait) {

 /* 竖屏 */
 #body {
  width: 100vw;
  height: 100vh;
  background: red;
 }
}

@media screen and (orientation:landscape) {

 /* 横屏 */
 #body {
  width: 50vw;
  height: 100vh;
  background: green;
 }
}

メタ タグ属性の設定

<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />

説明に誤りがあれば訂正してください!

おすすめ

転載: blog.csdn.net/m0_70015558/article/details/128528569