你的位置:首页 > 网页设计

[网页设计]刚入前端整合的一个手机端页面适配+预加载+获取资源加载进度等的一个小模板


       刚入前端不久,之前主要学的是pc端的布局,到公司之后负责的主要是移动段页面,刚开始时为了使页面适应移动端不同的屏幕大小采用的是百分比加媒体查询的方式,做完一个项目之后,感觉非常不好,虽然最后也基本使页面做到了适配。所以做完这个项目之后,我就在网上查找各种屏幕适配的方案,最终找到了一个通过js控制使页面整体缩放的方案,还有一个就是通过js实时检测屏幕大改变html根字体大小的rem布局方案。目前我在使用的是缩放的方案。整体代码基本上是整合的是大牛们分享的一些实用代码,如有什么bug欢迎提出,共同进步!

HTML代码

 1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4   <meta charset="UTF-8"> 5   <meta name="viewport" content="width=640"> 6   <meta content="yes" name="apple-mobile-web-app-capable"> 7   <meta content="black" name="apple-mobile-web-app-status-bar-style"> 8   <meta content="telephone=no" name="format-detection"> 9   <link rel="stylesheet" href="css/comment.css">10   <link rel="stylesheet" href="css/index.css">11   <!--适配js代码-->12   <script src="js/mobile-util.js"></script>13   <script src="js/jquery-2.1.4.min.js"></script>14   <!--获取资源加载进度获取插件-->15   <script src="js/pace.js"></script>16   <title>手机页面模板</title>17 </head>18 <body>19 <div class="box">20 21 </div>22 23 <!--加载进度显示-->24 <div class="load" >25   <div class="con-load">26     <img src="img/loading.png" alt="">27     <p></p>28   </div>29 </div>30 <!--旋转提示-->  <!-- 选择禁止横屏或竖屏显示-->31 <div id="orientLayer" class="mod-orient-layer">32   <div class="mod-orient-layer__content">33     <i class="icon mod-orient-layer__icon-orient"></i>34     <div class="mod-orient-layer__desc">为了更好的体验,请使用竖屏浏览</div>35   </div>36 </div>37 </body>38 <script src="js/index.js"></script>39 </html>

css初始化代码

 1 body, nav, dl, dt, dd, p, h1, h2, h3, h4, ul, ol, li, input, button, textarea, footer { 2   margin: 0; 3   padding: 0 4 } 5 *:not(input,textarea) { 6   -webkit-touch-callout: inherit; 7   -webkit-user-select: auto; 8 } 9 html{10   width: 100%;11   height: 100%;12 }13 14 body {15   font-family: "微软雅黑", Arial, sans-serif ,Microsoft Yahei,Simsun;16   font-size: 14px;17   color: #333;18   background-color: red;19   width: 100%;20   height: 100%;21   position: relative;22   -webkit-tap-highlight-color: rgba(0, 0, 0, 0);23   -webkit-text-size-adjust: none;24   min-width: 320px;25   max-width: 640px;26   overflow: hidden;27   margin: 0 auto;28 }29 30 h1, h2, h3, h4, h5, h6 {31   font-size: 100%32 }33 34 form {35   display: inline36 }37 38 ul, ol {39   list-style: none40 }41 42 a {43   text-decoration: none;44   color: #1a1a1a45 }46 47 a:hover, a:active, a:focus {48   color: #1c5aa2;49   text-decoration: none;50 }51 52 a:active {53   color: #aaa;54 }55 a, img {56   -webkit-touch-callout: none; /* 禁止长按链接与图片弹出菜单 */57 }58 img {59   vertical-align: middle;60   border: 0;61   -ms-interpolation-mode: bicubic;62 }63 64 button, input, select, textarea {65   font-size: 100%;66   vertical-align: middle;67   outline: none;68 }69 70 textarea {71   resize: none72 }73 74 button, input[type="button"], input[type="reset"], input[type="submit"] {75   cursor: pointer;76   -webkit-appearance: button;77   -moz-appearance: button78 }79 80 input:focus:-moz-placeholder, input:focus::-webkit-input-placeholder {81   color: transparent82 }83 84 button::-moz-focus-inner, input::-moz-focus-inner {85   padding: 0;86   border: 087 }88 89 table {90   border-collapse: collapse;91   border-spacing: 092 }

加载动画,选择横竖屏显示css代码

 1 .box{ 2   width:100%; 3   height:100%; 4   background-color: #0abdff; 5   /*height:1010px;*/ 6   overflow: hidden; 7 } 8  9 /*加载进度样式*/ 10 .load { 11   width: 100%; 12   height: 100%; 13   position: absolute; 14   top: 0; 15   left: 0; 16   background-color: black; 17   z-index: 11; 18   display: -webkit-box; 19   -webkit-box-pack: center; 20   -webkit-box-align: center; 21 } 22  23 .con-load { 24   position: relative; 25   width: 100px; 26   height: 100px; 27 } 28  29 .load img { 30   width: 100px; 31   position: absolute; 32   top: 0; 33   left: 0; 34   z-index: 13; 35   -webkit-animation: rotate 1s linear infinite; 36   animation: rotate 1s linear infinite 37 } 38  39 .load p { 40   width: 80px; 41   height: 80px; 42   font-size: 25px; 43   font-weight: bold; 44   color: rgba(255, 255, 255, 0.65); 45   line-height: 80px; 46   position: absolute; 47   top: 10px; 48   left: 10px; 49   z-index: 14; 50   text-align: center; 51 } 52  53 /*加载进度动画*/ 54 @-webkit-keyframes rotate { 55   0% { 56     -webkit-transform: rotate(0deg); 57     -ms-transform: rotate(0deg); 58     transform: rotate(0deg); 59   } 60   50% { 61     -webkit-transform: rotate(180deg); 62     -ms-transform: rotate(180deg); 63     transform: rotate(180deg); 64   } 65   100% { 66     -webkit-transform: rotate(360deg); 67     -ms-transform: rotate(360deg); 68     transform: rotate(360deg); 69   } 70 } 71  72 @keyframes rotate { 73   0% { 74     -webkit-transform: rotate(0deg); 75     -ms-transform: rotate(0deg); 76     transform: rotate(0deg); 77   } 78   50% { 79     -webkit-transform: rotate(180deg); 80     -ms-transform: rotate(180deg); 81     transform: rotate(180deg); 82   } 83   100% { 84     -webkit-transform: rotate(360deg); 85     -ms-transform: rotate(360deg); 86     transform: rotate(360deg); 87   } 88 } 89 /*横竖屏代码*/ 90 /* 样式放在结尾,防止 base64 图片造成拥塞 */ 91 @-webkit-keyframes rotation { 92   10% { 93     transform: rotate(90deg); 94     -webkit-transform: rotate(90deg) 95   } 96   50%, 60% { 97     transform: rotate(0deg); 98     -webkit-transform: rotate(0deg) 99   }100   90% {101     transform: rotate(90deg);102     -webkit-transform: rotate(90deg)103   }104   100% {105     transform: rotate(90deg);106     -webkit-transform: rotate(90deg)107   }108 }109 110 @keyframes rotation {111   10% {112     transform: rotate(90deg);113     -webkit-transform: rotate(90deg)114   }115   50%, 60% {116     transform: rotate(0deg);117     -webkit-transform: rotate(0deg)118   }119   90% {120     transform: rotate(90deg);121     -webkit-transform: rotate(90deg)122   }123   100% {124     transform: rotate(90deg);125     -webkit-transform: rotate(90deg)126   }127 }128 129 #orientLayer {130   display: none;131 }132 133 @media screen and (min-aspect-ratio: 13/9) {134   #orientLayer {135     display: block;136   }137 138   body {139     width: 100%;140     height: 100%;141   }142 }143 144 .mod-orient-layer {145   display: none;146   position: fixed;147   height: 100%;148   width: 100%;149   left: 0;150   top: 0;151   right: 0;152   bottom: 0;153   background: #000;154   z-index: 9997155 }156 157 .mod-orient-layer__content {158   position: absolute;159   width: 100%;160   top: 45%;161   margin-top: -75px;162   text-align: center163 }164 165 .mod-orient-layer__icon-orient {166   background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIYAAADaCAMAAABU68ovAAAAXVBMVEUAAAD29vb////x8fH////////x8fH5+fn29vby8vL////5+fn39/f6+vr////x8fH////////+/v7////09PT////x8fH39/f////////////////////x8fH///+WLTLGAAAAHXRSTlMAIpML+gb4ZhHWn1c2gvHBvq1uKJcC6k8b187lQ9yhhboAAAQYSURBVHja7d3blpowFIDhTUIAOchZDkre/zE7ycySrbUUpsRN2/1fzO18KzEqxEVgTiZNfgmmtxRc8iaR8HNe8x4BtjQePKayYCIoyBSgvNNE1AkNSHqZyLqk97EgUCCHBzZ5mkg7ScvIJuIyOyXBRFxgpqWZyGsAZLB1KjsJi8nutHU4JCRbFRH8tmirI9k8Jx2sqNs8K/m0LQkrktO2crgcgXGB4AiTEsB0hJfo9MGgX7CGcYiYwQxmMOOvZwRhBG8tCoMXjBDeXvWCEcHbi14wgCBmMIMZzGAGM5jxETNwzMAxA8cMHDNwzMAxA8cMHDNwzMAxA8cMHDNwzMAxY6E2rUQxnH2tz9cirlJFwFBJedaPnUv0M7++egPDE8iAJcIDmxwH5wwv9vUviw2kLbVO3TJU5uul/EyB0FoLp4x60PdGUd3qPurrWyjGGTc05u+1dcgI7/+tCCPARWGhH7o5Y7RCf+bH9ctXLp6v2BVDxfqz0oPXeSVaNtINo/1SXDv4dck8IIkbhtC2ol+iouEonTBCbYvVMnXOjxww6s/RFrBUpXHh/gw1rHj5d/qhYn9Gpk2FWh6xRBRX5Oj3Znh2Sq49/L6+y8pB26q9GbE2dbA2mVbx6I+7MfBglLCttm73ZQi7AD3iL4HqjFYJHSPRppqaUaJ3ATpGa+ckpGak2hRRMyqjGMkvl+xyFeSMwjAqcsZgGDdyhl0oNTnDN4yenJGZFGxNChP5/Y3efh6SM2rDOJMzboYxkDMqwyjIGcIw6F+io2FU1IxIm1JqRmgXSkvNKNCXeTpGrU0JNSO2c6LIGPgCS8AuDHz9ta0SXWDtxoDRH+MqlbC2Dt2G2JFRadtQZt2qq/orGowdGb2euxYiqWEpVWhTBnszoNAPdStuQwxqf0aocdWKW4Z+DfszIh8pxJqbuCE4YAC+4bm0evtipjpgJHeFnyyt1Ku2xa0bhjxr27p75rECNwyI9ZwvXkHq+7aTaMEV44YYy/spfgjgjNHaWW+GeUhGEX7tLlVinIFDDSgnOwhi1V6bU0b6tVS9eAERe863g4dRrtiHdc6o+nn5vtyVVgR79Cqt4uL6gfHPQyGqtP2vf7HADGbcYwaOGThm4JiBYwaOGThm4JiBYwaOGThm4JiBYwaOGThm4JiBYwaOGThm4JjhtOM+J/AgT008yDMkN/dPP9hzS8zAMQN3OEYeekp5YU7KOKXwVXqiY+QS7smcinGKABWdiBgpPJTSMHJ4KidhhPBUSMLw4CmPhKHgKUXCkHsygum71ftNSgCX6bsl8FQyfbcL5EdYsDk0R3j7aiA5wpt5AjKg/2gLJEBD/0Hf2OOf/vRrj6z/7GtP4B3nMKyjHA12kIPSjnJs3FEO0TvKkYJHOWCR+rjJH0Vn6fI5PjNbAAAAAElFTkSuQmCC');167   display: inline-block;168   width: 67px;169   height: 109px;170   transform: rotate(90deg);171   -webkit-transform: rotate(90deg);172   -webkit-animation: rotation infinite 1.5s ease-in-out;173   animation: rotation infinite 1.5s ease-in-out;174   -webkit-background-size: 67px;175   background-size: 67px176 }177 178 .mod-orient-layer__desc {179   margin-top: 20px;180   font-size: 15px;181   color: #fff182 }

终端检测与资源预加载js代码

 1 /** 2  * Created by w on 2016/8/16. 3 */ 4 //  终端检测函数 5 var ua = parseUA(); 6 function parseUA() { 7   var u = navigator.userAgent; 8   var u2 = navigator.userAgent.toLowerCase(); 9   return { //移动终端浏览器版本信息10     trident: u.indexOf('Trident') > -1, //IE内核11     presto: u.indexOf('Presto') > -1, //opera内核12     webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核13     gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核14     mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端15     ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端16     android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或uc浏览器17     iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器18     iPad: u.indexOf('iPad') > -1, //是否iPad19     webApp: u.indexOf('Safari') == -1, //是否web应该程序,没有头部与底部20     iosv: u.substr(u.indexOf('iPhone OS') + 9, 3),21     weixin: u2.match(/MicroMessenger/i) == "micromessenger",22     taobao: u.indexOf('AliApp(TB') > -1,23   };24 }25 // 资源预加载  图片,音频,视频,js,css等文件资源都可以26 var images = new Array();27 preload(28   "http://stg-smartlearning.com/download/css3d-engine-master/img/yauncheng.png",29   "http://stg-smartlearning.com/download/css3d-engine-master/img/dupian.png",30   "http://stg-smartlearning.com/download/css3d-engine-master/img/feidaoshoushu.png",31   "http://stg-smartlearning.com/download/css3d-engine-master/img/yuanchengkanhu.png",32   "http://stg-smartlearning.com/download/css3d-engine-master/img/shangmentiyan.png",33   "http://stg-smartlearning.com/download/css3d-engine-master/img/yihudaojia.png",34   "http://www.stg-smartlearning.com/download/city/video/guSheng.mp3",35   "http://www.stg-smartlearning.com/download/www/city/video/flash1.mp4",36   "http://www.stg-smartlearning.com/download/www/city/video/flash2.mp4",37   "http://www.stg-smartlearning.com/download/www/city/video/haitong.mp4",38   "http://www.stg-smartlearning.com/download/www/city/video/hang1.mp4",39   "http://www.stg-smartlearning.com/download/www/city/img/1241362.jpg",40   "http://www.stg-smartlearning.com/download/www/city/img/haitong.png",41   "http://www.stg-smartlearning.com/download/www/city/img/ht.png"42 );43 function preload() {44   for (i = 0; i < preload.arguments.length; i++) {45     images[i] = new Image();46     images[i].src = preload.arguments[i]47   }48 }

屏幕适配js代码

/** * Created by w on 2016/7/18. *//** * MobileWeb 通用功能助手,包含常用的 UA 判断、页面适配、search 参数转 键值对。 * 该 JS 应在 head 中尽可能早的引入,减少重绘。 * * fixScreen 方法根据两种情况适配,该方法自动执行。 *   1. 定宽: 对应 meta 标签写法 -- <meta name="viewport" content="width=750"> *     该方法会提取 width 值,主动添加 scale 相关属性值。 *     注意: 如果 meta 标签中指定了 initial-scale, 该方法将不做处理(即不执行)。 *   2. REM: 不用写 meta 标签,该方法根据 dpr 自动生成,并在 html 标签中加上 data-dpr 和 font-size 两个属性值。 *     该方法约束:IOS 系统最大 dpr = 3,其它系统 dpr = 1,页面每 dpr 最大宽度(即页面宽度/dpr) = 750,REM 换算比值为 16。 *     对应 css 开发,任何弹性尺寸均使用 rem 单位,rem 默认宽度为 视觉稿宽度 / 16; *       scss 中 $ppr(pixel per rem) 变量写法 -- $ppr: 750px/16/1rem; *           元素尺寸写法 -- html { font-size: $ppr*1rem; } body { width: 750px/$ppr; }。 */window.mobileUtil = (function(win, doc) {  var UA = navigator.userAgent,    isAndroid = /android|adr/gi.test(UA),    isIos = /iphone|ipod|ipad/gi.test(UA) && !isAndroid, // 据说某些国产机的UA会同时包含 android iphone 字符    isMobile = isAndroid || isIos; // 粗略的判断  return {    isAndroid: isAndroid,    isIos: isIos,    isMobile: isMobile,    isNewsApp: /NewsApp\/[\d\.]+/gi.test(UA),    isWeixin: /MicroMessenger/gi.test(UA),    isQQ: /QQ\/\d/gi.test(UA),    isYixin: /YiXin/gi.test(UA),    isWeibo: /Weibo/gi.test(UA),    isTXWeibo: /T(?:X|encent)MicroBlog/gi.test(UA),    tapEvent: isMobile ? 'tap' : 'click',    /**     * 缩放页面     */    fixScreen: function() {      var metaEl = doc.querySelector('meta[name="viewport"]'),        metaCtt = metaEl ? metaEl.content : '',        matchScale = metaCtt.match(/initial\-scale=([\d\.]+)/),        matchWidth = metaCtt.match(/width=([^,\s]+)/);      if ( !metaEl ) { // REM        var docEl = doc.documentElement,          maxwidth = docEl.dataset.mw || 640, // 每 dpr 最大页面宽度          dpr = isIos ? Math.min(win.devicePixelRatio, 3) : 1,          scale = 1 / dpr,          tid;        docEl.removeAttribute('data-mw');        docEl.dataset.dpr = dpr;        metaEl = doc.createElement('meta');        metaEl.name = 'viewport';        metaEl.content = fillScale(scale);        docEl.firstElementChild.appendChild(metaEl);        var refreshRem = function() {          var width = docEl.getBoundingClientRect().width;          if (width / dpr > maxwidth) {            width = maxwidth * dpr;          }          var rem = width / 16;          docEl.style.fontSize = rem + 'px';        };        win.addEventListener('resize', function() {          clearTimeout(tid);          tid = setTimeout(refreshRem, 300);        }, false);        win.addEventListener('pageshow', function(e) {          if (e.persisted) {            clearTimeout(tid);            tid = setTimeout(refreshRem, 300);          }        }, false);        refreshRem();      } else if ( isMobile && !matchScale && ( matchWidth && matchWidth[1] != 'device-width' ) ) { // 定宽        var  width = parseInt(matchWidth[1]),          iw = win.innerWidth || width,          ow = win.outerWidth || iw,          sw = win.screen.width || iw,          saw = win.screen.availWidth || iw,          ih = win.innerHeight || width,          oh = win.outerHeight || ih,          ish = win.screen.height || ih,          sah = win.screen.availHeight || ih,          w = Math.min(iw,ow,sw,saw,ih,oh,ish,sah),          scale = w / width;        if ( scale < 1 ) {          metaEl.content = metaCtt + ',' + fillScale(scale);        }      }      function fillScale(scale) {        return 'initial-scale=' + scale + ',maximum-scale=' + scale + ',minimum-scale=' + scale + ',user-scalable=no';      }    },    /**     * 转href参数成键值对     * @param href {string} 指定的href,默认为当前页href     * @returns {object} 键值对     */    getSearch: function(href) {      href = href || win.location.search;      var data = {},reg = new RegExp( "([^?=&]+)(=([^&]*))?", "g" );      href && href.replace(reg,function( $0, $1, $2, $3 ){        data[ $1 ] = $3;      });      return data;    }  };})(window, document);// 默认直接适配页面mobileUtil.fixScreen();

 所有代码打包下载:http://files.cnblogs.com/files/wanggenzhen/phone.rar