解决方案涉及到的知识点:
viewport
媒体查询(media query)
Javascript window.matchMedia
响应式图片
栅格布局
顶部导航
测试工具
iOS和Android自带的浏览器都是基于webkit内核,所以我们可以使用viewport属性和media
query技术实现网站的响应性。
viewport
在
之中添加viewport元数据标签。
width=device-width 实现屏幕适配,页面绘制根据触屏大小变化,保持一致。
initial-scale 表示初始缩放。
Js代码
maximum-scale 表示最大缩放比例,1意味着不能进行缩放。
user-scalable=no
禁用页面缩放(zooming)功能。禁用缩放后,用户只能滚动屏幕,让你的网站看上去更像原生应用。
注意,这种方式我们并不推荐所有网站使用,还是要看你自己的情况而定!
Js代码
媒体查询(media
query)
根据不同的分辨率,引用不用的css
Css代码
media="screen and (max-device-width: 480px)"
href="shetland.css" />
media="screen and (max-device-width: 480px)"
href="shetland.css" />
Bootstrap3的实现 http://v3.bootcss.com/css/#grid-media-queries ,
以下是LESS方法的实现
Js代码
/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { ... }
/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { ... }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { ... }
/* Small devices (tablets, 768px and up) */
@media (min-width: @screen-sm-min) { ... }
/* Medium devices (desktops, 992px and up) */
@media (min-width: @screen-md-min) { ... }
/* Large devices (large desktops, 1200px and up) */
@media (min-width: @screen-lg-min) { ... }
Javascript window.matchMedia
用CSS3解决的确很方便,但某些场景下仍然需要JS技术。
Js代码
if (window.matchMedia("(min-width: 400px)").matches) {
// The screen width is 400px or wider.
} else {
// The screen width is less than 400px.
}
if (window.matchMedia("(min-width: 400px)").matches) {
// The screen width is 400px or wider.
} else {
// The screen width is less than 400px.
}
状态改变时监听
Js代码
function setup_for_width(mql) {
if (mql.matches) {
// The screen width is 400px or wider. Set up or change things
// appropriately.
} else {
// The screen width is less than 400px. Set up or change things
// appropriately.
}
}
var width_mql = window.matchMedia("(min-width: 400px)");
// Add a listener for when the result changes
width_mql.addListener(setup_for_width);
// And share the same code to set things up with our current state.
setup_for_width(width_mql);