手机自适应

<script type="text/javascript">

自定义rem的值,取到屏幕实际宽度/10,window.devicePixelRatio是设备上物理像素

var rem = document.documentElement.clientWidth * window.devicePixelRatio / 10;

重置html的fontsize

document.documentElement.style.fontSize = rem + "px";
添加meta标签及其属性;
var e = document.createElement("meta");
e.setAttribute("name","viewport");
e.setAttribute("content","width=" + document.documentElement.clientWidth * window.devicePixelRatio + ",user-scalable=no");
document.head.appendChild(e);
</script>
<div style="width: 5rem; height: 5rem;background: #777;">

</div>



/**
  * @file: wx-flexible.js V1.0.0;
  * @author: yy;
  * @copyright: 基于 lib-flexible.js | MIT License;
  * @doc:
  * 1.文档读取时自动执行,没有依赖;
  * 2.推荐作为第一个加载的js文件;
  * 3.设定屏幕宽度:重置viewport大小为设备像素*设备dpr;
  * 4.重置rem:屏幕宽度的十分之一,同时还原body字号为14px;
  * 5.设置html的dpr属性,以防在某些场景下使用(如:特别设置阅读字体);
  * 6.理论上,可以在所有移动设备上使用。目前只测试了大部分设备的微信浏览器;
  **/
   
  ~(function() {
  function setting() {
  // viewport的宽度设置为视口大小乘以设备dpr,固定初始1倍缩放
  var meta = document.createElement("meta"),
  dpr = window.devicePixelRatio,
  screenW = window.screen.width* dpr + "px",
  _time = null;
  meta.setAttribute("name","viewport");
  meta.setAttribute("content","user-scalable=no,width="+ parseFloat(screenW));
  document.head.appendChild(meta);
   
  // 为html设置一个dpr属性,为以后计算作为参考
  document.documentElement.setAttribute('data-dpr', dpr);
   
  // 重置rem方法
  function refreshRem() {
  var rem = parseFloat(screenW)/ 10;
  document.documentElement.style.fontSize= rem + 'px';
  }
   
  // 监听pageshow,防止存缓存中读取
  window.addEventListener('pageshow',function(e) {
  if (e.persisted) {
  clearTimeout(_time);
  _time = setTimeout(refreshRem, 300);
  }
  });
   
  // 监听方式,重置body字号
  document.addEventListener('DOMContentLoaded',function() {
  document.body.style.fontSize= 14 + 'px';
  });
   
  // 直接调用,保证rem被重置
  refreshRem();
  }
   
  var userAgent = window.navigator.userAgent,
  isMoblie = (!!userAgent.match(/iphone/i))|| (!!userAgent.match(/ipad/i))|| (!!userAgent.match(/Android/i));
  if (!isMoblie) {
  throw new Error("请在移动端打开!");
  }
  setting();
  })(); //直接执行,防止jQuery的ready优先调用出现错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值