设计稿一般宽度是750px,是在iphone6下的两倍。我们知道,rem是根据根元素字体大小,也就是html的字体来进行布局,我们只要调用这个JS函数,就可以根据屏幕大小改变根元素字体大小,用rem实现手机页面的自动缩放。
//根据屏幕大小改变根元素字体大小 (function(doc, win) { var docEl = doc.documentElement, resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize', recalc = function() { var clientWidth = docEl.clientWidth; if(!clientWidth) return; if(clientWidth >= 750) { clientWidth=750; docEl.style.fontSize = '100px'; } else { docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'; } docEl.style.fontSize = 100 * (clientWidth / 750) + 'px'; }; if(!doc.addEventListener) return; win.addEventListener(resizeEvt, recalc, false); doc.addEventListener('DOMContentLoaded', recalc, false); })(document, window);
HTML代码
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="utf-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> 6 <link rel="stylesheet" type="text/css" href="style.css"> 7 </head> 8 <body> 9 <div class="book-wrap"> 10 <div class="ele-book"> 11 <script type="text/javascript" src="global.js"></script> 12 <div class="book-author"> 13 <div class="book"> 14 <img src="img/book1.png"> 15 <div class="grade">评分:9.2</div> 16 <p>儿童行为心理学</p> 17 </div> 18 <div class="author">吴莎</div> 19 </div> 20 <div class="book-author"> 21 <div class="book"> 22 <img src="img/book1.png"> 23 <div class="grade">评分:9.2</div> 24 <p>儿童行为心理学把力气花在你想要的生活</p> 25 </div> 26 <div class="author">吴莎</div> 27 </div> 28 <div class="book-author authorR"> 29 <div class="book"> 30 <img src="img/book1.png"> 31 <div class="grade">评分:9.2</div> 32 <p>把力气花在你想要的生活对吗</p> 33 </div> 34 <div class="author">爱德华</div> 35 </div> 36 37 </div> 38 </div> 39 <script type="text/javascript" src="global.js"></script> 40 </body> 41 </html>
CSS代码
.book-wrap { 7rem; height: 3.81rem; // background-color: pink; border-radius: 10px; padding: 0.1rem; border: 1px solid pink; } .book-wrap .ele-book { position: relative; } .book-wrap .ele-book .book-author { float: left; margin-right: 0.5rem; 2rem; } .book-wrap .ele-book .book-author .book img { 2rem; height: 2rem; } .book-wrap .ele-book .book-author .book .grade { position: absolute; top: 1.6rem; 2rem; height: 0.4rem; font-size: 0.24rem; line-height: 0.4rem; background-color: #999999; text-align: center; color: #fff; opacity: 0.9; filter: alpha(opacity=80); } .book-wrap .ele-book .book-author .book p { height: 0.8rem; 2rem; line-height: 0.4rem; font-size: 0.28rem; overflow: hidden; margin: 0 0 0.3rem 0; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; word-break: break-all; } .book-wrap .ele-book .book-author .author { font-size: 0.24rem; color: #808080; margin-top: 0.2rem; padding-left: 0.4rem; height: 0.33rem; line-height: 0.33rem; background: url('img/author.png') no-repeat; background-size: 0.33rem; } .book-wrap .ele-book .book-author.authorR { margin-right: 0; }