移动端屏幕适配+事件+常见问题解决
移动端屏幕适配
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
移动端屏幕适配与响应式的区别
移动端屏幕适配:
移动端
宽高% / rem
字体px
宽高都随着屏幕变化等比例变化
响应式:
pc+移动端
宽%
高、字体:px
宽度等比例变化,高度不变
简单适配方案:
simple.js
(function () { 'use strict'; setremunit(); window.addeventlistener('resize', setremunit); function setremunit() { var docel = document.documentelement; var ratio = 18.75; var viewwidth = docel.getboundingclientrect().width || window.innerwidth; docel.style.fontsize = viewwidth / ratio + 'px'; } })();
通用适配方案:
flexible.js
(function () { 'use strict'; // dpr->scale = 1 / dpr var docel = document.documentelement, viewportel = document.queryselector('meta[name="viewport"]'), dpr = window.devicepixelratio || 1, maxwidth = 540, minwidth = 320; dpr = dpr >= 3 ? 3 : (dpr >= 2 ? 2 : 1); docel.setattribute('data-dpr', dpr); docel.setattribute('max-width', maxwidth); docel.setattribute('min-width', minwidth); var scale = 1 / dpr, content = 'width=device-width, initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'; if (viewportel) { viewportel.setattribute('content', content); } else { viewportel = document.createelement('meta'); viewportel.setattribute('name', 'viewport'); viewportel.setattribute('content', content); document.head.appendchild(viewportel); } setremunit(); window.addeventlistener('resize', setremunit); function setremunit() { var ratio = 18.75; var viewwidth = docel.getboundingclientrect().width || window.innerwidth; if (maxwidth && (viewwidth / dpr > maxwidth)) { viewwidth = maxwidth * dpr; } else if (minwidth && (viewwidth / dpr < minwidth)) { viewwidth = minwidth * dpr; } docel.style.fontsize = viewwidth / ratio + 'px'; } })();
通用适配案例源码:
预览图
index.html
<!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>通用适配应用</title> <link rel="stylesheet" href="css/base.css"> <link rel="stylesheet" href="css/icons.css"> <link rel="stylesheet" href="css/index.css"> <script src="js/flexible.js"></script> </head> <body> <header class="header-container"> <div class="navbar"> <div class="navbar-left"> <i class="iconfont icon-scan"></i> </div> <div class="navbar-center"> <div class="searchbox"> <div class="searchbox-prepend"> <i class="iconfont icon-search"></i> </div> <input type="text" class="searchbox-input" placeholder="开学季有礼,好货5折起"> <div class="searchbox-append"> <i class="iconfont icon-close"></i> </div> </div> </div> <div class="navbar-right"> <i class="iconfont icon-msg"></i> </div> </div> </header> <div class="main-container"> <div class="slider-container"> <img src="img/slider/1.jpg" alt="slider"> </div> <nav class="nav-container"> <ul class="nav"> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/1.png" alt="nav" class="nav-img"> <span class="nav-text">团购</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/2.png" alt="nav" class="nav-img"> <span class="nav-text">一元购</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/3.png" alt="nav" class="nav-img"> <span class="nav-text">优惠券</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/4.png" alt="nav" class="nav-img"> <span class="nav-text">教育</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/5.png" alt="nav" class="nav-img"> <span class="nav-text">旅行</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/6.png" alt="nav" class="nav-img"> <span class="nav-text">在线订餐</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/7.png" alt="nav" class="nav-img"> <span class="nav-text">庆典</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/8.png" alt="nav" class="nav-img"> <span class="nav-text">秒杀</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/9.png" alt="nav" class="nav-img"> <span class="nav-text">拍卖</span> </a> </li> <li class="nav-item"> <a href="###" class="nav-link"> <img src="img/nav/10.png" alt="nav" class="nav-img"> <span class="nav-text">服务</span> </a> </li> </ul> </nav> <div class="recommend-container"> <ul class="recommend"> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/1.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">欧派整体橱柜定制简约现代</p> <p class="recommend-origprice"> <del>¥2000.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">1000</strong></span> <span class="recommend-count">985件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/2.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">创维55吋4k超高清hdr</p> <p class="recommend-origprice"> <del>¥2999.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">2299</strong></span> <span class="recommend-count">63件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/3.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">【到手259元】苏泊尔 5l电压力锅</p> <p class="recommend-origprice"> <del>¥799.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">299</strong></span> <span class="recommend-count">1908件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/4.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">三只松鼠坚果礼包</p> <p class="recommend-origprice"> <del>¥125.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">108</strong></span> <span class="recommend-count">9532件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/5.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">蓝月亮洗衣液12斤</p> <p class="recommend-origprice"> <del>¥133.40</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">89.9</strong></span> <span class="recommend-count">5399件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/6.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">福临门葵花玉米油</p> <p class="recommend-origprice"> <del>¥109.90</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">89.9</strong></span> <span class="recommend-count">6294件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/7.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">tp-link 全千兆端口双频无线路由器</p> <p class="recommend-origprice"> <del>¥179.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">169</strong></span> <span class="recommend-count">4255件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/8.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">【前1800名再减50】家用高压洗车机</p> <p class="recommend-origprice"> <del>¥790.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">268</strong></span> <span class="recommend-count">1599件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/9.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">德国鲁茜rusch迷你婴儿辅食机 宝宝</p> <p class="recommend-origprice"> <del>¥898.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">159</strong></span> <span class="recommend-count">881件已售</span> </p> </a> </li> <li class="recommend-item"> <a href="###" class="recommend-link"> <p class="recommend-pic"> <img src="img/recommend/10.jpg" alt="recommend" class="recommend-img"> </p> <p class="recommend-name">西域之尚红枣500g*5袋</p> <p class="recommend-origprice"> <del>¥89.00</del> </p> <p class="recommend-info"> <span class="recommend-price">¥<strong class="recommend-price-num">29.9</strong></span> <span class="recommend-count">15049件已售</span> </p> </a> </li> </ul> </div> </div> <div class="tabbar-container"> <ul class="tabbar"> <li class="tabbar-item tabbar-item-active"> <a href="###" class="tabbar-link"> <i class="iconfont icon-home"></i> <span>首页</span> </a> </li> <li class="tabbar-item"> <a href="###" class="tabbar-link"> <i class="iconfont icon-category"></i> <span>分类页</span> </a> </li> <li class="tabbar-item"> <a href="###" class="tabbar-link"> <i class="iconfont icon-cart"></i> <span>购物车</span> </a> </li> <li class="tabbar-item"> <a href="###" class="tabbar-link"> <i class="iconfont icon-personal"></i> <span>个人中心</span> </a> </li> </ul> </div> </body> </html>
base.css
* { box-sizing: border-box; padding: 0; margin: 0; } body { font-size: 12px; color: #5d655b; } a { font-size: 12px; color: #686868; text-decoration: none; -webkit-tap-highlight-color: transparent; } input { font-size: 12px; border: none; background: none; outline: none; } [data-dpr="2"] body, [data-dpr="2"] a, [data-dpr="2"] input { font-size: 24px; } [data-dpr="3"] body, [data-dpr="3"] a, [data-dpr="3"] input { font-size: 36px; } li { list-style: none; } img { vertical-align: top; border: none; width: 100%; }
icons.css
@font-face { font-family: "iconfont"; src: url('../fonts/iconfont.eot?t=1522237704791'); /* ie9*/ src: url('../fonts/iconfont.eot?t=1522237704791#iefix') format('embedded-opentype'), /* ie6-ie8 */ url('data:application/x-font-woff;charset=utf-8;base64,d09grgabaaaaabfeaasaaaaagkgaaqaaaaaaaaaaaaaaaaaaaaaaaaaaaabhu1vcaaabcaaaadmaaabcsp6z7u9tlziaaae8aaaaqgaaafzw7kpqy21hcaaaayaaaadwaaac3hdqdndnbhlmaaaccaaadecaabh09z93/mhlywqaaa64aaaamqaaadyq3yfraghlyqaaduwaaaagaaaajafza9hobxr4aaapdaaaabsaaabmtc7/+2xvy2eaaa8oaaaakaaaacgovix8bwf4caaad1aaaaadaaaaiaenamhuyw1laaapcaaaauuaaajtplt+fxbvc3qaabc4aaaaiqaaalvqptpuejxjygrgyobikgpqywb0cfmjyebgyggaajamy05meijqdmodyrgaaq4gzooiagckiwnpahicy2bkywkcwmdkwmhuyxsggyghh0izvmywyurgygbiygvmwaoc0lxtgbwykl7emdf8b2aakgwnqgfgkbwa2tsl1qaaejzfkjfuwkaqrf8gb+leiq0fdyqsqrscgjyjcbcugmqfuaefx+asf12mikrf/vjtueskitkrz+2ovjwz+wfai4cb+bafkl6qepgpborzazz3+qinnvu8a1dgw5ivg045y8sfl1xxyz2pezcp+dytlxeprarvqo5fulwv+y8rvaxeuknfj93qfrp1/yihncgxxhaj1binf1hvjyl9x+nbqppvdz1nxoakwmrpyhpygb0rwjv4m42jyehu6nxbmympymvkblgwuytle1pflzfp4nbimxbvehwori4i74z8rd4yoyt8nviy3dqg/gapw2evejylvwumhmdx7zqe/8zu7oz89np7m7md0d3ele/2e9y9dy0esr1f8kjjperjz1kiy1q0kyqmbss2ltk04wgqitkqrjmydiosgbtgbbmeaqgoashwwjij4wqika8v0/nyiglyqhq4cwzrhqnevsmkrgga5hauu7q6urqr+nv1nreiufyp9gwaira5iuytrbkbebbr4ce5alsivp2rgvmrhm9o0iiikllg1+kcel5ou41ok/restqgcuvovhqdqm5f0g7nc31ouawabd53e7o6kqafbzutfx8z3s49b04pgdhmj+oliqw7ubbkt+jpddadpiulgibzhg8k4ajnkokiivelgpfzxi6ncsxqs1fux/5eoz++99hwa4wqpwccpg1wvpz8yokzm/e7mxotdfzkjermlhgm2vcjh2szsy+e/0twt0rbr9brghknekrmxkmhzbfs7ytrpeqd10tctq5rq1thpestmdsrtptoebzkpfcrixoi6/cicx9n7hinj446in4hsr+mx+f7vabtgmb9bz4i2kfwu9bboxjfyd92vvqgjn0hgjm6kv/qdnnm7jex5uphnqzc85zhpjmr/fwu2amp2z1/o8fhgi1sb+duvt35a/fcdwh1l3zykvuahh36sh0u6swubgue8gjp0/rfab/tcylpnrgdi5jlva7phgtmoyvltoifwuukvadae+ehjsu215nrumawoe9y/etbaphyzzaeif5fxpgfuu++p/yzj57//d5y7s/u4rhds/1l+kpya7eek9z9y8v3czaz3vjaeaodwk8vxfoz36e9if7l5cvxl1cthjret+n9rwco7gv2evaidmakwbn/epmhn7e7gtpqu2n3zj20ohn2+djpbds0fhz9z56nfwijpmcrnfeqdxni+eecs69zbjubvzscjfgbgtjudrqu59iu12y4tlgj/ldv6ans1j4fybll/dbqd3au9janbdqhvvgliyxjmmtjgp2wbsbc41ktldkedasaxhvptr0pdm+aimu4cpmrro+roq8g3jmizgbmd5lthepj1soijincovgwnzjasfzwgqe/u58zdhhzz+jg6l/b+6a/qbug/swcdyk3hr+e7pdtxodguh6a6yfofio/jeuspmvdkkgdh30bcz0getjglsj7yqr5eclbd9sm84dj2mlqvehlcgitgcdgbylu2sy1q/d67n8bbh/xrfckiubvv+oqebucguqek7hmdw1+husmrvh5tn7d+kox8r3vqm9bnw/z9qfvjeel4ub1wfo8rd4o3/kkspr3ppgetlxgzcqgusb429wvesxg/gbk3q8bgviaywjxvva+nw1x8re+2eca+ppw83xusg/bbmbego3c6stqdohnse4wgfthq9enzwrggxaw916nv2mozdhq9chmsgnpd7pizdyz/ljnxslq7jpyzftfwnaw1tgbmudzuhm9yt1gdp8bqfeu7uvt5lidvudt0zbc68vgddoarix4qq58xtk+vogawxyrv88xwraxrd8srnf6fyy0hwrid/v2wlarrejjt8hohjzt27n6o0ii0mc+bfgqfuazfc48cmxaj2l8v01kfvzoabqjgkrenpafskwokgpkffocogesulhdxpjaoshgfk1t/v/wt/+f42ht6c4swfjnwkkwmj+dh4x16vsnem84ncy3vny9h1xx3tezmuc23aazfux/opiqdjh3h3qxlumau0cquaelv1ae/gh9ct0j2ngkplebbcqwmghvr4fmjnctn1pviuw2m7lz4+yz/sb9jny/sx9m1kz9luypohlxxqfpuxruweosjl4uqxo9/jsl+707kzsuf1uqgexdooeorw9aiocxupav9hgaigvcnqiiyl9saatcmalswu8qwjbxoifinyftj3wd+d/jnzi9vg1don6tmsanawtkh4a8et0xo/4jstriit+m32smgasd7zfyqjjnd+grdntgfo5qxggf4/wwshvrshtowsyiw2c48jqjlosjr/bjueociqtrdv1jdhgbs0s6ju4xxrcmz6evctcp+kr8/njiz2hj5voi8qxpxfhy2yu+fbqbajrjpzeesj/9xx1yrtizwf/4ju8/wrt90vjtvjl5het3t03cfneqttnbdxbwib3xr+gjxc5+afcsnh1m+jppio/hb8n1e6d3wa9/w5yuntj3ny82kfqpxrcep++j/zizfskisxoyhatn9g+lmbynnazymuv//bv9bwojrk6q30ondg/pblpur4qe1wgbevcrgilqierhhjuyauidqiyjafmyuyrcqwzwgkhlcuvgepkifcpwonvsdbzqh+eyagmmghjimdj+soaqpef+f+am+dma52hebmh3b+jdadiaeqvq9fz2wwcchbelggvbvjhuzvstfhkpkrb97nao297feli8n0hsb+gkzd3ec1upsf/td2qarzoftvjpvb1psah3csbve4shkgbjfnrca7iswkf1icypxfrxdja5vv7kerst8x9tebg/mxfvvhtlumj6yjptlvovvzzvfnlvporx4wh+rraxnx9qfdp9dpepmbffpnpx7izuzsuu3eetcz5pwfbuzblhlc34rqmhiiw1bst7lvu7ihpvv+qtan2ylffhkmwblfex7hty8kiswhpk6cj+tgsrwj/ajuoneggrao/2hlbvjiwqpyxotadu+z7fm0vbwxueo6yyo4tfxrvztvsqlz5ocqqdvpsvzyvdrz44mrarny+ukkqzrhf2nlimez37z+othw82wnkcluatb0sggh8bjjyndzcxgavuvoepjypzpx5mh0oprhxwz1z0eejpwt2zsgi+zprijb9jnjm7i9jrgp19gtnfjbpbycgcprw18vagfqqcj7k70xzmy+xwvlkcy5dlixmdfury4rwbhda1cl8uoljdgsedg0am20vcisqxa2nvc7rrpbf6u96qrh633nhvbkvu4bpv7ly1wy2u3v4m3chyorcl4yi7qykgwcgliy1rctjq9ppypsdzqvk+pep1scvwp6knwb+f8vth8reow/j2/mittvef3i6m8n8rbuax/5qfkurbc/gf6jraowohclt28t/tkkbiu6jlbb2ukxfalsfjua2w7xejsxfysyxauxr0e+cxyz7714d+ukj/z+290cwykpajmnxtld03rcoyjky8t9ztpkgk+ugketdrae8cldqnentzthl4h9h0/ez8ztmnt56b3wdofv1o/mbrw4epqubo4rdfjaecoqmnoorju4ryrta+nfmtobyu4id1yfefiwqkqc6ihmi55v0tmtxflerwncg6a4aiorrwe1my7f0pnjttrdmspvhr84fvqcgmvmkvpwaug/h7uio3zj/rl+goazo95apkmhprmcvmwfravj92me8pbimqouwp1t8a3nqkyqzdfibxrmkmngoz9cpgcadtnodaks28jj4v1gk6d7bxnohqibjanqao0jzuyaz0xgkcmqaaxsyencagejh+0rvzi580pvy+nm7kghzviqyqu7vapift0uwnv9wvyz1luqbuak95ddwu9wxbscp+vrkgucvvmdoae+wytmdhhrgtc7n4g66pkhfifw5ljojvjflycfn+w2e6nzlvqnr9rnnldbx3az69y0sihgzeejogbwuxu2qfplrxfhwxd8m0n8+4ja64jogeyecq3vbgvp/nzox8a0lbohzmcrtxzisyl3e8us5z+fmpscfm147pu46kc8dey+z5tpto57lsvjgu738wa9pvzfa5ommz2quvaiy3evhjjq92tlqnmcrvi9auqqqtr3q6xmvkq5pcwe5jshevzkpk8stoi3dtv9d+qh9fs/gunyx3k4+rt6ff+loypmryxys3tjb4phvz4s0mw5gbtnm1xmbvevbic9hfpweihfyiljzqbh3w18dlz7ogz10sesqtqckukxiddrga78v1gt4wtymjhaj/ywtfjv6qds/+4yarughckkuldun85m7dstyl6rp6v8ls78zuudk2mlv5rwkhm4w/yxxefsfj2rjx/ymjhmzhy+k1evqrf5f1/ualaj/k+jvmpfizqh2o+vayglwlg522p7nvlavw7bvy1gwsgfjmcpxfx3z4qa0fjf3ox9p5mpgcynf6qlnmz7p+kjrox2c61z/yx7v/af8aejxjygrgyabi9uzb9fh8nl8zufkyqodaw0ucmpr/7//twriy3yfcdgymkcgasnmmjwaaahicy2bkygbu+n/aempi8v83awmlawnqbauiawb8mgs6ejxjywbgyh7jwmdcqaj2awjgdph/vwfvqwn0aaaaaaaadgdeavab4gj8avidtgqgbeaeyaxobhogrgckb0qh3ghecpp4ngngzgbgegbyw8dfaajmqmwfzv8h8xkahy0b8aaaahiczy9ntsmweivf+gekeqqoyifkbwibkp0rq25yvgr3xxtfpk6bkokjx63ua3aejsajoalcgdvwscebnpbh37x5y08a3oahho7flferpvwyo3inf7gxrln/eg6qx4sbaonvuex9tdjhm6bcbxrheypxugl2hhdhdx18cndwju/hovuv4qb5w7ijo/wkt9dx6si+5l5xui1hl/bhvi+cxqnlqcwhysktob+cmv7vkowt0uqca1vejlodof9ju51pw91t7ndd5yivwzoqcas6syzkrdnq0aub5/jrrxejhoqm5vhj/rbgao5xbyuldowxqhhkimro6dtvzvsvsupcxntwpc3ndfsu1p9zhqec9m9cu7qy0nk6t4e9xxtsdxqrbsueldsrxs1jerjcxta2velqatzlv44relzrit8oz0j/aalabsgaaab4ng2m2w6cmbafe2shihfxb+u6awjhsbsx+vdcfhvetjljgbdxpxr3nxybfccuqobry4sgo+xxwbennhhbfs1udm9/d/w0netzutyprmocppkjhfsmuas5mhsaplvedpfvq6ky+czpnfc6zspu0zqh3ou8xduljzqeeh3fs8yobmqhmxnfhbqomaaaaa==') format('woff'), url('../fonts/iconfont.ttf?t=1522237704791') format('truetype'), /* chrome, firefox, opera, safari, android, ios 4.2+*/ url('../fonts/iconfont.svg?t=1522237704791#iconfont') format('svg'); /* ios 4.1- */ } .iconfont { font-family: "iconfont" !important; font-size: 16px; font-style: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .icon-backtop:before { content: "\e689"; } .icon-personal:before { content: "\e610"; } .icon-scan:before { content: "\e609"; } .icon-clear:before { content: "\e622"; } .icon-msg:before { content: "\e7a8"; } .icon-category:before { content: "\e7f9"; } .icon-search:before { content: "\e616"; } .icon-delete:before { content: "\e6ac"; } .icon-service:before { content: "\e643"; } .icon-setting:before { content: "\e64c"; } .icon-back:before { content: "\e60f"; } .icon-shop:before { content: "\e624"; } .icon-close:before { content: "\e60c"; } .icon-more:before { content: "\e85c"; } .icon-home:before { content: "\e699"; } .icon-collect:before { content: "\e78c"; } .icon-cart:before { content: "\e635"; }
index.css
/*-- 布局 start --*/ html, body { width: 100%; height: 100%; } /*header*/ .header-container { top: 0; background-color: rgba(222, 24, 27, 0.9); } .header-container, .tabbar-container { position: fixed; left: 0; z-index: 1000; width: 100%; height: 2.5rem; } /*tabbar*/ .tabbar-container { bottom: 0; background-color: #fff; box-shadow: 0 0 10px 0 rgba(154, 141 ,141, 0.6); } /*main-container*/ .main-container { padding: 2.5rem 0; background-color: #eee; } /*nav-container*/ .nav-container { background-color: #fff; margin-bottom: 0.5rem; } /*-- 布局 end --*/ /*-- 组件 start --*/ /*navbar*/ .navbar { display: flex; height: 100%; } .navbar-left, .navbar-center, .navbar-right { display: flex; justify-content: center; align-items: center; height: 100%; } .navbar-left, .navbar-right { width: 2.2rem; } .navbar-center { flex: 1; } .navbar-left .iconfont, .navbar-right .iconfont { color: #fff; font-size: 1.2rem; } /*searchbox*/ .searchbox { display: flex; width: 100%; height: 1.6rem; border-radius: 0.8rem; background-color: #fff; } .searchbox-prepend, .searchbox-input, .searchbox-append { height: 100%; } .searchbox-prepend, .searchbox-append { display: flex; justify-content: center; align-items: center; width: 1.6rem; } .searchbox-input { flex: 1; } .searchbox .iconfont { color: #ccc; font-size: 0.9rem; font-weight: bold; } /*nav*/ .nav { display: flex; flex-wrap: wrap; padding: 0.8rem 0 0.4rem; } .nav-item { width: 20%; margin-bottom: 0.4rem; } .nav-link { display: block; text-align: center; } .nav-img { width: 2.25rem; height: 2.25rem; margin-bottom: 0.2rem; } .nav-text { display: block; } .tabbar, .tabbar-item, .tabbar-link { height: 100%; } .tabbar { display: flex; } .tabbar-item { width: 25%; } .tabbar-link { display: flex; flex-direction: column; justify-content: center; align-items: center; } .tabbar-link .iconfont { font-size: 1.2rem; } .tabbar-item-active .tabbar-link { color: #de181b; } /*-- 组件 end --*/ /*-- 内容 start --*/ /*recommend*/ .recommend { display: flex; flex-wrap: wrap; justify-content: space-between; } .recommend-item { width: 49.333333%; background-color: #fff; box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.12); margin-bottom: 0.25rem; } .recommend-link { display: block; width: 100%; height: 100%; } .recommend-pic { width: 100%; margin-bottom: 0.4rem; } .recommend-img { width: 100%; height: 9.25rem; } .recommend-name, .recommend-origprice, .recommend-info { padding: 0 0.25rem; margin-bottom: 0.4rem; } .recommend-name { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } .recommend-origprice { color: #ccc; } .recommend-info { display: flex; justify-content: space-between; align-items: center; } .recommend-price { color: #e61414; } .recommend-price-num { font-size: 20px; } [data-dpr="2"] .recommend-price-num { font-size: 40px; } [data-dpr="3"] .recommend-price-num { font-size: 60px; } .recommend-count { color: #999; } /*-- 内容 end --*/
移动端事件
touchstart 进入目标区域
touchmove 在目标区域移动
touchend 离开目标区域
event对象
<script> var boxel = document.getelementbyid('box'); boxel.addeventlistener('touchstart', handlestart, false); boxel.addeventlistener('touchmove', handlemove, false); boxel.addeventlistener('touchend', handleend, false); function handlestart(ev) { console.log('touchstart', ev); console.log(ev.touches, ev.targettouches, ev.changedtouches); var touch = ev.changedtouches[0]; console.log(touch.pagex, touch.pagey); } function handlemove(ev) { console.log('touchmove'); } function handleend(ev) { console.log('touchend', ev); } </script>
其他触摸事件
hammer.js自己去官网下哈
<script src="js/hammer.min.js"></script> <script> var boxel = document.getelementbyid('box'); var hammertime = new hammer(boxel); hammertime.on('pan swipe tap doubletap press pinch rotate', function(ev) { console.log(ev.type); }); </script>
利用hammer做出滑动切换的幻灯片
index.html
<!doctype html> <html lang="zh-cn"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <title>幻灯片的滑动切换</title> <link rel="stylesheet" href="css/slider.css"> </head> <body> <div id="slider" class="slider"> <div class="slider-item-container"> <div class="slider-item"> <a href="###" class="slider-link"> <img src="img/1.jpg" alt="slider" class="slider-img"> </a> </div> <div class="slider-item"> <a href="###" class="slider-link"> <img src="img/2.jpg" alt="slider" class="slider-img"> </a> </div> <div class="slider-item"> <a href="###" class="slider-link"> <img src="img/3.jpg" alt="slider" class="slider-img"> </a> </div> <div class="slider-item"> <a href="###" class="slider-link"> <img src="img/4.jpg" alt="slider" class="slider-img"> </a> </div> <div class="slider-item"> <a href="###" class="slider-link"> <img src="img/5.jpg" alt="slider" class="slider-img"> </a> </div> </div> </div> <script src="js/hammer.min.js"></script> <script src="js/slider.js"></script> <script> var slider = new slider(document.getelementbyid('slider'), { initindex: 0, // 初始显示第几张幻灯片,从0开始 speed: 300, // 幻灯片的切换速度 hasindicator: true // 是否需要指示器indicator }); var hammer = new hammer(slider.getitemcontainer()); var isswiping = false; hammer.on('panmove', function (ev) { var distance = ev.deltax + slider.getdistancebyindex(slider.getindex()); slider.move(distance); }); hammer.on('panend', function (ev) { if (isswiping) return; var distance = ev.deltax + slider.getdistancebyindex(slider.getindex()); var index = getindexbydistance(distance); slider.to(index); }); // 根据容器移动的距离获取索引 function getindexbydistance(distance) { if (distance > 0) { return 0; } else { return math.round(-distance / slider.getdistanceperslide()); } } hammer.on('swipeleft', function (ev) { // next isswiping = true; slider.next(function () { isswiping = false; }); }); hammer.on('swiperight', function (ev) { // prev isswiping = true; slider.prev(function () { isswiping = false; }); }); </script> </body> </html>
slider.css
/*css reset*/ * { box-sizing: border-box; padding: 0; margin: 0; } img { border: none; vertical-align: top; } a { -webkit-tap-highlight-color: transparent; } /*slider*/ .slider { overflow: hidden; position: relative; width: 100%; height: 183px; } .slider-item-container, .slider-item, .slider-link, .slider-img { width: 100%; height: 100%; } .slider-item-container { display: flex; transition: transform 0; } .slider-item { flex-shrink: 0; } .slider-link { display: block; } .slider-indicator-container { position: absolute; bottom: 10px; width: 100%; text-align: center; } .slider-indicator { display: inline-block; width: 8px; height: 8px; background-color: #000; opacity: 0.2; border-radius: 50%; margin-right: 8px; } .slider-indicator-active { background-color: #007aff; opacity: 1; }
slider.js
function slider(el, options) { var defaults = { initindex: 0, speed: 300, hasindicator: false }; this.options = {}; this.options.initindex = typeof options.initindex !== 'undefined' ? options.initindex : defaults.initindex; this.options.speed = typeof options.speed !== 'undefined' ? options.speed : defaults.speed; this.options.hasindicator = typeof options.hasindicator !== 'undefined' ? options.hasindicator : defaults.hasindicator; this.el = el; this.itemcontainer = el.queryselector('.slider-item-container'); this.items = this.itemcontainer.children; this.distanceperslide = this.items[0].offsetwidth; this.minindex = 0; this.maxindex = this.items.length - 1; // this.index = this.options.initindex; this.index = this._adjustindex(this.options.initindex); this.move(this.getdistancebyindex(this.index)); if (this.options.hasindicator) { this._createindicators(); this._setindicatoractive(this.index); } } slider.prototype.to = function (index, cb) { this.index = index; this._settransitionspeed(this.options.speed); this.move(this.getdistancebyindex(this.index)); var self = this; this.itemcontainer.addeventlistener('transitionend', function () { self._settransitionspeed(0); if (typeof cb === 'function') { cb(); } }, false); if (this.options.hasindicator) { this._setindicatoractive(this.index); } }; slider.prototype._settransitionspeed = function (speed) { this.itemcontainer.style.transitionduration = speed + 'ms'; }; slider.prototype.prev = function (cb) { this.to(this.index - 1, cb); }; slider.prototype.next = function (cb) { this.to(this.index + 1, cb); }; slider.prototype._adjustindex = function (index) { if (index < this.minindex) { index = this.minindex; } else if (index > this.maxindex) { index = this.maxindex; } return index; }; slider.prototype.move = function (distance) { this.itemcontainer.style.transform = 'translate3d(' + distance + 'px, 0, 0)'; }; slider.prototype.getdistancebyindex = function (index) { return -index * this.distanceperslide; }; slider.prototype._createindicators = function () { var indicatorcontainer = document.createelement('div'); var html = ''; indicatorcontainer.classname = 'slider-indicator-container'; for (var i = 0; i <= this.maxindex; i++) { html += '<span class="slider-indicator"></span>'; } indicatorcontainer.innerhtml = html; this.el.appendchild(indicatorcontainer); }; slider.prototype._setindicatoractive = function (index) { this.indicators = this.indicators || this.el.queryselectorall('.slider-indicator'); for (var i = 0; i < this.indicators.length; i++) { this.indicators[i].classlist.remove('slider-indicator-active'); } this.indicators[index].classlist.add('slider-indicator-active'); }; slider.prototype.getitemcontainer = function () { return this.itemcontainer; }; slider.prototype.getindex = function () { return this.index; }; slider.prototype.getdistanceperslide = function () { return this.distanceperslide; };
移动调试和终端检测
移动端检测:
<script> // 切换android、iphone、ipad console.log(navigator.useragent); var ismobile = navigator.useragent.match(/android|iphone|ipod|ipad/i); if (ismobile) { location.href = 'https://m.test.com'; } else { location.href = 'https://www.test.com'; } </script>
移动端常见问题:
浏览器兼容性:
html5兼容处理 html5shiv
自己去官网下载哈
<script src="js/html5shiv.min.js"></script>
不同浏览器前缀:
display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; ----------------------- <script> var requestanimationframe = window.requestanimationframe || window.webkitrequestanimationframe || window.mozrequestanimationframe || window.orequestanimationframe || window.msrequestanimationframe || function (fn) { settimeout(fn, 16); }; requestanimationframe(function () { console.log(1); }); </script>
modernizr 检测浏览器的css3和html5的属性,从而通过css来解决兼容性问题
自己去官网下载哈
<script src="js/modernizr.js"></script>
click 300ms 延迟问题解决:
<script src="js/fastclick.js"></script> <script> if ('addeventlistener' in document) { document.addeventlistener('domcontentloaded', function() { fastclick.attach(document.body); }, false); } </script>
单行文字溢出省略
.text-ellipsis { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
多行文字溢出省略
.multiline-ellipsis { overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; white-space: normal !important; word-wrap: break-word; }
水平居中和垂直居中方案:
1 容器宽高自适应 没有指定宽高 内容撑开
1-1 内联元素或者内联块元素 不能设置宽高 内容撑开
1-1-1 文字水平垂直居中 多行文字 用padding撑开
display: inline/inline-block; padding: 30px 20px;
1-1-2 容器水平垂直居中 内联元素
left: 50%; top: 50%; transform: translate(-50%, -50%);
1-2 块元素 不能设置宽高
1-2-1 文字水平垂直居中 多行文字
display: block; text-align: center; padding: 30px 0;
1-2-2 容器水平垂直居中 块元素
position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%);
2 指定容器宽高宽高
2-1 内联元素 不能设置宽高 内容撑开
2-2 内联块元素 设置宽高
2-2-1 文字水平垂直居中 多行文字
display: inline-block; width: 300px; height: 100px; text-align: center; line-height: 100px; 多行文字 display: flex; justify-content: center; align-items: center;
2-2-2 容器水平垂直居中 内联块元素
position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); margin-left: -150px; margin-top: -50px;
2-3 块元素 设置宽高
2-3-1 文字水平垂直居中 多行文字
display: block; width: 300px; height: 100px; text-align: center; line-height: 100px;
2-3-2 容器水平垂直居中 块元素
margin: 0 auto; position: absolute; left: 50%; top: 50%; margin-left: -150px; margin-top: -50px;
多行文字 display: flex; justify-content: center; align-items: center;