简单说说rem适配和响应式

53 阅读1分钟

JS实现监听屏幕尺寸变化

    window.onresize = function (e) {
        console.log(`当前屏幕宽宽度为:${document.documentElement.clientWidth}`);
    }

最原始的rem适配,屏幕宽度小于1024,进入rem响应式。最大fontSize为40

    document.addEventListener('DOMContentLoaded', function () {
        const html = document.querySelector('html')
        if (window.innerWidth < 1024) {
            const maxFontSize = 40; // 最大字体大小
            let fontSize = window.innerWidth / 10
            if (fontSize > maxFontSize) {
                fontSize = maxFontSize
            }
            html.style.fontSize = fontSize + "px";
        } else {
            html.style.fontSize = "16px";
            console.log(html.style.fontSize)
        }
    })

再说说媒体查询,下面是nav,该nav有三个对应样式,在不同屏幕尺寸下显示不同样式

    .nav {
      display: none;
    }
    @media screen and (min-width: 768px) {
      .nav {
        display: flex;
      }
    }

    @media screen and (min-width: 1024px) {
      .nav {
        display: flex;

      }

      .nav ul {
        display: flex;
      }
    }

也可以引入css文件

  <link rel="stylesheet" href="style640.css" media="screen and (min-width: 640px)">

目前响应式框架tailwindcss非常好 由于web应用功能太过丰富,很多公司选择移动端一个网站,PC端一个网站,响应式应用较少。个人网站推荐使用。