H5 前端页面适配响应式

辞职有半个月了,面试了几家公司,还在挣扎中。。。。

不废话,H5页面适配成响应式,可以用百分比或者rem.

rem是相对于html根元素的单位,可以根据根元素的大小做出等比缩放,

通常,假如设置,html{font-size:100px;},那么,1rem=100px;

 

那么如何做到响应式呢?我们需要一点JS代码:

(function(win) {
    var doc = win.document;
    var docEl = doc.documentElement;
    var tid;

    function refreshRem() {
        var width = docEl.getBoundingClientRect().width;
		//alert(width);
        if (width > 650) { // 最大宽度
           // width = 540;
		   docEl.style.fontSize=100+"px";
        }else{
			docEl.style.fontSize=40+"px";
		}
        //var rem = width / 10; // 将屏幕宽度分成10份, 1份为1rem
        //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();

})(window);

  代码可以根据自己的需要进行修正,需要请拿走,不谢。。。

posted @ 2016-10-21 21:48  Terre  阅读(3547)  评论(0编辑  收藏  举报

风光无限好