原生js H5适配它来了 保姆级教学

49 阅读1分钟

废话不说,上代码

js核心代码

1.这里面的所有750改为设计图的大小

2.不改也可以,吧设计图大小改为750

也就是手机屏想象成宽度750rem

我的方法:

        1.把psd设计图文件上传到蓝湖 然后尺寸改为750

        

 然后都用布局

设计图大小给多少就是多少 例如

 

//重点 重点 重点
function AutoPage() {
  document.documentElement.style.fontSize =
    (document.documentElement.clientWidth * 100) / 750 + "px";
  setFontSize();
}
AutoPage();
window.addEventListener("resize", AutoPage, false);
if ($(window).width() > 750) {
  document.documentElement.style.fontSize = 97.6389 + "px";
}
function setFontSize() {
  var clientWidth = document.documentElement.clientWidth,
    timer;
  console.log(clientWidth);
  if (!clientWidth) return;
  document.documentElement.style.fontSize =
    (document.documentElement.clientWidth * 100) / 750 + "px";
  if (
    window.getComputedStyle(document.getElementsByTagName("html")[0]).fontSize
  ) {
    var size = window
      .getComputedStyle(document.getElementsByTagName("html")[0])
      .fontSize.split("p")[0];
    if (size * 1.2 < (document.documentElement.clientWidth * 100) / 750) {
      document.documentElement.style.fontSize =
        (1.25 * document.documentElement.clientWidth * 100) / 750 + "px";
    }
    console.log(document.documentElement.style.fontSize);
  }
}


//附加代码 可写可不写
//Android微信中,借助WeixinJSBridge对象来阻止字体大小调整
(function () {
  if (
    typeof WeixinJSBridge == "object" &&
    typeof WeixinJSBridge.invoke == "function"
  ) {
    handleFontSize();
  } else {
    if (document.addEventListener) {
      document.addEventListener("WeixinJSBridgeReady", handleFontSize, false);
    } else if (document.attachEvent) {
      //IE浏览器,非W3C规范
      document.attachEvent("onWeixinJSBridgeReady", handleFontSize);
    }
  }

  function handleFontSize() {
    // 设置网页字体为默认大小
    WeixinJSBridge.invoke("setFontSizeCallback", {
      fontSize: 0,
    });
    // 重写设置网页字体大小的事件
    WeixinJSBridge.on("menu:setfont", function () {
      WeixinJSBridge.invoke("setFontSizeCallback", {
        fontSize: 0,
      });
    });
  }
})();

附加代码可写可不写

/* ios兼容微信字体变大,页面错乱问题 */
body {
    /*重要 ios兼容微信字体变大,页面错乱问题 */
	-webkit-text-size-adjust: 100% !important;
    /*不重要*/
	background-color: #ffffff;
	background-image: url(../imges/dots.png);
	background-repeat: repeat;
}