移动端横竖屏问题--兼容iPhone、Android

来源:互联网 发布:seo网站推广招聘 编辑:程序博客网 时间:2024/06/06 18:53

移动端竖屏效果好做,可是如果在浏览器横屏的话页面瞬间变丑,怎么办呢,我来分享一下我的方法,希望对大家有所帮助。
首先,在页面内容的外面增加一个盒子,css样式如下:

.main{    position: absolute;    top: 0;bottom: 0;left: 50%;    margin-left: -1.8rem; // 居中    width: 3.6rem;    overflow-y:auto; }

其次,js如下:

function set_html_fontsize() {    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);    var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);    var width = w > h ? h : w;    width = w > 720 ? 720 : w    document.getElementsByTagName("html")[0].style.cssText = 'font-size: ' + ~~(width*100000/36)/10000+"px;";  }  window.orientationchange = function(){set_html_fontsize()};  window.onresize = function(){set_html_fontsize()};  set_html_fontsize();

注:上面代码中,
window.orientationchange = function(){set_html_fontsize()};是屏幕旋转时执行
window.onresize = function(){set_html_fontsize()};是浏览器大小发生改变时执行,测试时需要。

下面,我们来看一个demo

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>点点勤工下载页</title>    <link rel="stylesheet" href="static/style/style.css">    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">    <script src="static/js/main.js"></script>    <script>        function set_html_fontsize() {          var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);          var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);          var width = w > h ? h : w;          width = w > 720 ? 720 : w          document.getElementsByTagName("html")[0].style.cssText = 'font-size: ' + ~~(width*100000/36)/10000+"px;";        }        window.orientationchange = function(){set_html_fontsize()};        window.onresize = function(){set_html_fontsize()};        set_html_fontsize();    </script>    <style type="text/css">        .webview{            position: absolute;top: 0;bottom: 0;left: 50%;margin-left: -1.8rem;width: 3.6rem;overflow-y:auto;        }        .main{            width: 3.6rem;height: 6.4rem;background:url(static/image/bg.png) top center no-repeat;            background-size: 100%;position: relative;        }        .btn{width: 2.1rem;height: .55rem;left: .75rem;position: absolute;background-size: 100%;}        .btn1{background-image:url(static/image/iphone.png);bottom:1.5rem;}        .btn2{background-image:url(static/image/android.png);bottom: .7rem;}    </style></head><body>    <div class="webview">        <div class="main">            <div href="" class="btn btn1"></div>            <div href="" class="btn btn2"></div>        </div>    </div></body></html>

如上所述,问题就搞定了。如有疑惑,敬请提问!

1 0
原创粉丝点击