YiluPHP
这家伙很懒,什么都没有留下...

经验 手机页面禁止横屏,手机页面只允许竖屏

浏览数 192821
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
<style type="text/css">
body{
    padding: 0;
    margin: 0;
    overflow: hidden; /*横屏时高出的滚动条隐藏掉*/
}
/*给予灰色背景方便察看识别*/
#demo{background-color: #ccc;}
.rotate {
    transform: rotate(-90deg);
}

</style>
</head>
<body>

<div id="demo">这里是内容</div>

<script src="/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
    (function rotate(){
       var orientation=window.orientation;
       if(orientation==90||orientation==-90){
            //因为马上获取的窗口宽高为旋转前的,计算需要用旋转后的,因此延迟到旋转后再运行以下代码
            setTimeout(function(){
                //横屏时长的为宽,短的为高
                var width = $(window).height() > $(window).width()?$(window).height():$(window).width();
                var height = $(window).height() < $(window).width()?$(window).height():$(window).width();
            // alert(width+'heng'+height)
                marginLeft = -(height - width)/2;
                marginTop = (height - width)/2;
              // alert("请使用竖屏访问!");
              $("#demo").addClass("rotate").css({width:height, height:width, marginLeft:marginLeft, marginTop:marginTop});
              $(document.body).css({height:height});
          }, 100);
       }
       else{
        setTimeout(function(){
            //横屏时长的为高,短的为宽
            var width = $(window).height() < $(window).width()?$(window).height():$(window).width();
            var height = $(window).height() > $(window).width()?$(window).height():$(window).width();
        // alert(width+'su'+height)
        $("#demo").removeClass("rotate").css({width:width, height:height, marginLeft:0, marginTop:0});
        }, 100);
       }
       window.onorientationchange=function(){
          rotate();
       };
})();
</script>
</body>
</html>
我来说说