js简单的移动端横竖屏适配

js简单的移动端横竖屏适配

1、先判断处于横屏还是竖屏状态:
简单的判断方式(不是很严谨):
竖屏: 宽度 < 高度;
横屏:宽度 > 高度;

function getWandH() {
  let W =  document.documentElement.clientWidth || document.body.clientWidth;
  let H =  document.documentElement.clientHeight || document.body.clientHeight;
  // width大于height即可视窗口宽度大于可视窗口高度时为横屏状态;
  return W / H > 1;
}

2、rem适配(以iPhone6/7/8 375*667为例):

function setRem() {
  if (getWandH()) {
    document.documentElement.style.fontSize = Math.min(screen.width, document.documentElement
    .getBoundingClientRect().width) / 667 * 16 + 'px';
  } else {
    const scale = document.documentElement.clientWidth / 750;
  	document.documentElement.style.fontSize = (baseSize * Math.min(scale, 2)) + 'px';
  }
}
<

猜你喜欢

转载自blog.csdn.net/start_sea/article/details/122598482