前端页面自适应大小,动态rem

欢迎点赞收藏⭐留言如有错误敬请指正!

任意浏览器的默认字体高都是16px,默认情况下html的1rem = 16px
前端页面自适应大小,动态rem_第1张图片
当页面设置为:

html {
  font-size: 100px;
}
body {
  font-size: 0.18rem;
}

此时:标题20px, 可设置为0.2rem ;图标宽度36px,可设置为0.36rem

由于rem是相对页面根元素html的大小,所以可以通过动态改变根元素的大小来全局改变页面元素的大小,从而达到自适应不同分辨屏幕的效果。动态改变根元素的代码如下:

var ScreenResize: any = {
  designWidth: 1920,
  designHeight: 1080,
  minHeight: 768,
  minWidth: 1280,

  resize: function () {
    scale: this.designWidth / this.designHeight;
    var htmlWidth = Math.max(document.documentElement.clientWidth, ScreenResize.minWidth)
    var htmlHeight = Math.max(document.documentElement.clientHeight, ScreenResize.minHeight);
    document.documentElement.style.fontSize = (htmlHeight / (ScreenResize.designHeight / 100)) + "px";
    document.documentElement.style.minHeight = ScreenResize.minHeight + "px";
    document.documentElement.style.minWidth = ScreenResize.minWidth + "px";
    document.documentElement.style.width = htmlWidth + "px";
    document.documentElement.style.height = htmlHeight + "px";
  }
};
ScreenResize.resize();

var throttle = function (func: any, delay: number) {
  var timer: any = null;
  var startTime = Date.now();
  return function () {
    var curTime = Date.now();
    var remaining = delay - (curTime - startTime);
    clearTimeout(timer);
    if (remaining <= 0) {
      func();
      startTime = Date.now();
    } else {
      timer = setTimeout(func, remaining);
    }
  }
}
window.addEventListener('resize', throttle(() => ScreenResize.resize(), 1000));

你可能感兴趣的:(前端优化,前端,性能优化)