移动端开发总结(1)

移动端布局一直是困扰我的一个大问题,特别是去年在某电商实习期间曾经做一个活动页做了好久好久好久,现在工作期间遇到活动页或者微信传播页也是必须要按时快速高质量任务的。
近期在做一个hybird项目的UAT,代码里出现了前辈们的各种不同的css写法,我必须要全部看懂然后再做修改,也是很蛋疼,所以周末在图书馆对遇到的坑做个总结吧。

常用单位

rem

[MDN]This unit represents the font-size of the root element.
这个单位代表了根元素的字体大小。
如果在document里面有html元素,即为根元素,通过在html上设置font-size,则可以使用rem来表示字体大小或者用来定义元素的高度、宽度等等。

下面是一段我写的简易媒体查询的代码,即通过css来实现自适应,font-size的取值最好为偶数,避免发生字体渲染问题。这里选用10px作为基础值是因为设计师以iphone6作为设计图标准,设计稿上宽度750px,iphone6实际宽度375px,这样手动rem换算只要设计稿px/10/2,很容易进行布局计算,其余的自适应完全交给浏览器去实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@media screen and (min-width:361px) {
html {
font-size:10px;
}
}
@media screen and (min-width:400px) {
html {
font-size:12px;
}
}
@media screen and (min-width:500px) {
html {
font-size:14px;
}
}
@media (-webkit-min-device-pixel-ratio:X){

}

上面的写法比较适合普遍性的适应,不能保证所有机器得到最精准的适配,而且当遇到对像素要求很高的设计师抠细节的时候,总不能给每个手机都做media quary吧,于是下面给出一段js实现的,通过获取屏幕实际可用区域控制root元素font-size大小的代码。

1
2
3
4
5
6
7
8
9
10
(function(){
var width = window.screen.width;
var rate = width/375;
var newFontSize = 'font-size:' + rate*10 + 'px';
document.getElementsByTagName('html').style = newFontSize;
}());

window.onload = function(){
document.getElementById('text').innerHTML = document.getElementsByTagName('html').style;
}

你也可以点击这里,查看我的在线demo。

em

[MDN]This unit represents the calculated font-size of the element. If used on the font-size property itself, it represents the inherited font-size of the element.
从元素进行font-size属性的继承,即获取父元素的字体大小进行设置。
通过在父元素上设置font-size,则可以使用em来表示字体大小或者用来定义子元素的高度、宽度等等。

vw、vh

[MDN]vw:1/100th of the height of the viewport.
[MDN]vh:1/100th of the width of the viewport.
[MDN]vmin:1/100th of the minimum value between the height and the width of the viewport.
[MDN]vmax:1/100th of the maximum value between the height and the width of the viewport.
vw、vh相对于屏幕的百分比,1vw是屏幕宽度的1%,1vh是屏幕高度的1%,由于屏幕是固定的,所以设置的百分比也是固定的。
要注意的是,如果带有弹出式键盘,则vh会自动改变,所以在需要调用设备原生键盘的时候,尽量不要使用vh

改变viewport

和用js改变html的font-size类似,也可以通过js来改变meta标签。

1
2
3
4
5
6
7
var width = window.screen.width/320;
var rate = width/375,
viewport = document.querySelector('meta[name=viewport]');

viewport.setAttribute('content',
viewport.getAttribute('content')
.replace(/(initial-scale)=[d.]?d/,'$1='+rate))

附录一js常用获取屏幕信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
网页可见区域宽:document.body.clientWidth
网页可见区域高:document.body.clientHeight
网页可见区域高:document.body.offsetWidth(包括边线的宽)
网页可见区域宽:document.body.offsetHeight(包括边线的高)
网页正文全文宽:document.body.scrollWidth
网页正文全文高:document.body.srcollHeight
网页被卷去的高:document.body.scrollTop
网页被卷去的左:document.body.scrollLeft
网页正文部分上:window.screenTop
网页正文部分左:window.screenLeft
屏幕分辨率的高:window.screen.height
屏幕分辨率的宽:window.screen.width
屏幕可用工作区高度:window.screen.availHeight
屏幕可用工作区宽度:window.srceen.availWidth

移动端开发总结(1)
https://guoningyan.com/2016/07/31/移动端开发总结(1)/
作者
Ningyan Guo
发布于
2016年7月31日
许可协议