Two solutions for front-end multi-screen adaptation

In large-screen development, the most common problem is multi-screen adaptation. Here are two simple and practical solutions.

1. Increase the scale of the outermost element

The outermost element here refers to the element that can contain all pages. We can set a fixed width and height for the outermost element, such as 1920 * 1080. Once the size of the large screen does not match the set size, it will be adapted to the large screen by scaling the corresponding multiple.
The specific code is as follows:

// 获取缩放倍率
getScale = () => {
    const  [width, height] = [1920, 1080];
    let widthScale = window.innerWidth / width;
    let heightScale = window.innerHeight / height;
    return [widthScale, heightScale];
};

// 设置缩放倍率
setScale = () => {
    const [widthScale, heightScale] = this.getScale();
    let containerDom = document.getElementById('container');
    containerDom.style.transform = `scale(${widthScale}${heightScale})`;
    containerDom.style.transformOrigin = 'left top';
};

componentDidMount() {
    this.setScale();
    this.windowResizeListener = window.addEventListener('resize', this.setScale);
}
componentWillUnmount() {
    window.removeEventListener('resize', this.windowResizeListener);
}

In this way, no matter what kind of large screen, it can be scaled to achieve adaptation. The disadvantage is that if the large screen aspect ratio is inconsistent with the set size aspect ratio, it will be distorted. When extreme aspect ratios are encountered, distortion may be severe.

There is a compromise solution. When the width scaling and height scaling ratios are in a certain range (here we take [0.7, 1.428]), normal scaling is performed; otherwise, the smaller magnification scaling is used. This treatment can ensure that the deformation is not serious, but it will leave a part of the blank space. code show as below:

setScale = () => {
    
    
  const [widthScale, heightScale] = this.getScale();
  let containerDom = document.getElementById('container');
  // 如果屏幕缩放变形不是太严重,则直接缩放
  const rate = widthScale / heightScale;
  if (rate >= 0.7 && rate <= 1.428) {
    containerDom.style.transform = `scale(${widthScale}${heightScale})`;
  } else {
    // 否则取最小的倍率缩放
    const scale = widthScale > heightScale ? heightScale : widthScale;
    containerDom.style.transform = `scale(${scale})`;
  }
  containerDom.style.transformOrigin = 'left top';
};

2. Rem is implemented with postcss-pxtorem

rem is the root element font size. Dynamically adjust the size of rem according to the screen size to achieve multi-screen adaptation. code show as below:

// rem.js
function setRem() {
  // 基准大小
  const baseSize = 100;
  let vW = window.innerWidth; // 当前窗口的宽度
  let basePc = baseSize / 1920;
  let rem = vW * basePc; // 以默认比例值乘以当前窗口宽度,得到该宽度下的相应font-size值
  document.documentElement.style.fontSize = rem + 'px';
}
// 初始化
setRem();
// 改变窗口大小时重新设置 rem
window.addEventListener('resize', () => {
  setRem();
});

However, when developing, it is time-consuming and labor-intensive to use rem to write styles. The best way is to write styles in px normally, and automatically complete the transformation from px to rem through the postcss-pxtorem plug-in. The specific treatment is as follows:

1. Install postcss-loader and postcss-pxtorem

npm install postcss-loader postcss-pxtorem --save-dev

After installation, you may encounter the problem of postcss-pxtorem requires PostCSS 8, which is caused by the high version of pxtorem, which can be solved by lowering the version of pxtorem. For details, please refer to the article: PostCSS plugin postcss-pxtorem requires PostCSS 8 problem solution

2. Configuration

pxtorem is a plugin for postcss, we configure it in postcss.config.js. code show as below:

// postcss.config.js
module.exports = {
    plugins: [
        require('postcss-pxtorem')({
            rootValue: 100,
            propList: ['*'],
            exclude: /node_modules/  //这里表示不处理node_modules文件夹下的内容
        })
    ]
}

Then we configure postcss-loader in webpack, the code is as follows:

// ...
rules:[
        {
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                "css-loader",
                "postcss-loader"
            ],
        },
        {
            test: /\.less$/,
            use: [
                MiniCssExtractPlugin.loader,
                "css-loader",
                "postcss-loader",
                "less-loader"
            ],
        },
    ]
// ...

其中, postcss-loader 是对 css 进行处理的, 因此放在 less 之前。 通过 postcss-pxtorem 处理后,所有的 px 都会被自动转成 rem。 我们配置的样式: alt 浏览器中的样式: alt 可以看到我们配置的样式从 px 转换成了 rem。

三、两种方式对比

scale 的方式,使用简单,但当目标屏幕与设置屏幕宽高比差距比较大的时候,使用 scale 缩放会导致字体、图片变形。如图: alt

rem 不会变形,但完全按照屏幕宽度缩放的,有时候可能底部空间剩余较多,或者底部空间不足出现滚动条。如图: alt

「参考资料:」 前端大屏项目的屏幕适配方案 webpack 配置 postcss-pxtorem PostCSS plugin postcss-pxtorem requires PostCSS 8 问题解决办法

本文由 mdnice 多平台发布

Guess you like

Origin blog.csdn.net/ppppppppppsd/article/details/128713294