移动页面缩放方法之(二)控制HTML

时间:2024-09-04 20:36:20
<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no,target-densitydpi=device-dpi"/>
<title>无标题文档</title>
<style>
*{
    padding:0;
    margin:0;
}
div{
    width:1000px;
    height:500px;
    margin:0 auto;
    line-height:500px;
    font-size:30px;
    text-align:center;
    color:#fff;
    background:red;
}
</style>
</head>

<body>
<div>我是测试的</div>
<script>
;(function(top){
    var doc=top.document;
    function setStyle(){
        for(var name in arguments[0]){
            var sName=name.charAt(0).toUpperCase()+name.substring(1);
            var sValue=arguments[0][name];
            this.style['Webkit'+sName]=sValue;
            this.style['Moz'+sName]=sValue;
            this.style['Ms'+sName]=sValue;
            this.style['O'+sName]=sValue;
            this.style[sName]=sValue;
        }
    }
    top.SetScale=function(width){
        this.bOk='orientation' in top?true:false;
        var resize=this.bOk?'orientationchange':'resize';
        this.obj=doc.querySelector('html');
        this.obj.style.width=width+'px';
        this.viewWidth=top.screen.width;
        this.viewHeight=top.screen.height;
        this.initWidth=width;
        this.scale=1;
        this.init()[resize]();
    };
    SetScale.prototype={
        init:function(){
            var width=this.bOk?this.viewWidth:this.obj.clientWidth;
            this.scale=width/this.initWidth;
            setStyle.call(this.obj,{
                transform:'scale('+this.scale+')',
                transformOrigin:'left top'
            });
            return this;
        },
        resize:function(){
            top.addEventListener('resize',this.init.bind(this),false);
        },
        orientationchange:function(){
            var _this=this;
            top.addEventListener('orientationchange',function(){
                var rotate=(top.orientation+90)/90%2;
                if(!rotate){
                    _this.scale=_this.viewHeight/_this.initWidth;
                }else{
                    _this.scale=_this.viewWidth/_this.initWidth;
                }
                setStyle.call(_this.obj,{
                    transform:'scale('+_this.scale+')',
                    transformOrigin:'left top'
                });
            },false);
        }
    };
    SetScale.prototype.constructor=SetScale;
    doc.addEventListener('DOMContentLoaded',function(){
        new SetScale(1000);
    },false);
})(parent);
</script>
</body>
</html>