<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;" name="viewport" /> <title>Title</title> <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script> <script> //-------------------------方法 - 小数点精度可能会产生误差,但几乎不会发生---------------- (function () { document.addEventListener('DOMContentLoaded', function () { var html = document.documentElement; var windowWidth = html.clientWidth; //如果设计搞的宽度 = 640px,设计一般用640*940 html.style.fontSize = windowWidth / 6.4 + 'px'; // 等价于html.style.fontSize = windowWidth / 640 * 100 + 'px'; }, false); })(); $(document).ready(function() { $("#bt").click(function() { alert("当前浏览器计算的宽度是"+$("#my_div").width() ); }); }); </script> <!--6.4的话就是全宽 (任何手机都能适配)--> <style> body { padding: 0rem; margin: 0rem; } div { width: 6.4rem; height:1rem; background-color: greenyellow} </style> <!------------------一般写法写法 -----------------
var winW = document.documentElement.clientWidth; var desW = 640; var fontSize = 100; var rem = desW/fontSize; if(winW>desW){//但前屏幕大于640,就不需要适配了320/ 640/100 = 6.4 winW=desW; } document.documentElement.style.fontSize = winW/rem+"px";</head><body> <button id="bt">ok</button> <div id="my_div">适配</div></body></html>