PC端项目兼容手机端

1,358 阅读1分钟

背景

开发中要求实现一个页面适配pc适配mobile,没有真实操作过记录一下。

方案

GPT推荐

  • 响应式布局
    • 使用 CSS 媒体查询 (采用)
    • 使用 Tailwind CSS
  • 视口单位 + REM 适配 + (采用
  • 组件化方案(PC 和 Mobile 组件分开)
  • 动态路由区分 PC 和 Mobile

推荐建议:

  • 如果 PC 和移动端 UI 结构相似推荐方案 1(响应式布局)

  • 如果 PC 和移动端适配需要更精准的缩放方案 2(REM + px 转换)

  • 如果 PC 和 Mobile 差异较大方案 3(不同组件)

  • 如果 PC 和 Mobile 完全不同方案 4(动态路由跳转)

实现

  1. 根据视口计算REM的值, 并监听视口变化
<!doctype html>
<html lang="en">
    <head>
        <!-- 这个必须要有 -->
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    </head>

    <body>
        <div id="app"></div>
    </body>
    <script>
        // 设置根元素的字体大小
        function setRootFontSize() {
            const width = window.innerWidth;
            const baseWidth = width > 768 ? 1920 : 375; // 根据ui设计图来设定,pc: 1920; mobile: 375
            const fontSize = (width / baseWidth) * 16; // 根据屏幕宽度设置字体大小,16px 是基础字体大小
            document.documentElement.style.fontSize = `${fontSize}px`; 
        }

        // 初始化
        setRootFontSize();

        // 在窗口大小变化时重新设置字体大小
        window.addEventListener('resize', setRootFontSize);
    </script>
</html>

2.pc以及mobile的设计图结构分析

一般使用 Flex 或者 Grid。我项目中使用的是Flex,但是觉得Grid更好一些。

遇到问题以及解决

  • 第三方组件样式问题
    • 问题 使用antd的组件时,在切换到移动端时,样式展示不一致问题
    • 解决 使用 css in js自定义组件样式,将一些px单位的值转为rem
    import styled from 'styled-components';
    import { Button } from 'antd'
    
    const CustomBtn = styled(Button)`
      // xxxxx
    `