h5屏幕适配

H5屏幕适配的三种方案

1-rem动态适配

通过获取屏幕宽度来设置html的fontSize,用rem来配置相关元素的宽高。

 remViewport()
        function remViewport(){
             const html = document.querySelector('html');
            const width =window.screen.width
            html.style.fontSize = width/7.5 +'px'
            //1rem = 100px
        }

如上我们已经将1rem等价于100px,在配置其它相关元素时,我们只需要对其进行相关换算就行。

2-动态改变meta viewport标签

通过获取屏幕的宽度来缩放页面

 fixWidth()
      window.addEventListener('resize',fixWidth)
      function fixWidth(){
          //屏幕宽度
          const width =window.screen.width

          //设计图宽度
          const fixedWidth = 750;
          const scale = width / fixedWidth;

          const meta = document.createElement('meta')
          meta.setAttribute('name','viewport')
    	  meta.setAttribute('content',`width=${fixedWidth},initial-scale=${scale}`)
          document.head.appendChild(meta)
      }

3-vw适配

1vw = 1%视口宽度,通过给rem赋值给vw,然后给相关元素配置rem

<!-- 设置图宽度为750px-->
html{
    font-size: 1rem;
}
<!-- 100/7.5=13.333333   1rem =13.333333vw     1rem = 100px--> 

版权声明:本文为y1506778504原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。