-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathscreenOrientation.js
65 lines (64 loc) · 2.34 KB
/
screenOrientation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
* 移动端网页强制横竖屏展示效果
* @author shineliang
* @create 2016/10/28 update 2016/11/10
*/
var screenOrientation = function(option){
var _this = this;
_this.option = {
'mode' : 'portrait',//portrait(竖屏)、landscape(横屏)
'id':'wrap',//最外层容器ID
'init':false,
'callback':false
};
for (var k in option) if(option[k] != '') _this.option[k] = option[k];
var obj = document.getElementById(_this.option.id);
var className = obj.className || " ";
var w_width = obj.clientWidth;
var w_height = obj.clientHeight;
var flag = 0;
var timer;
if(_this.option.mode == "portrait")
var cssBlock =
'.'+_this.option.id+'_screenOrientation{-webkit-transform: rotateZ(-90deg) !important; transform: rotateZ(-90deg); position:relative;}';
else
var cssBlock =
'.'+_this.option.id+'_screenOrientation{-webkit-transform: rotateZ(90deg) !important; transform: rotateZ(90deg); position:relative;}';
var style = document.createElement("style");
style.type = "text/css";
style.textContent = cssBlock;
document.getElementsByTagName("head").item(0).appendChild(style);
var _width=(window.innerWidth > 0) ? window.innerWidth : screen.width;
var _height=(window.innerHeight > 0) ? window.innerHeight : screen.height;
_this.modifyDetec = function(){
if((_height<_width&&_this.option.mode == "portrait")||(_height>_width&&_this.option.mode == "landscape")&& flag==0){
obj.style.width = _height+"px";
obj.style.height = _width+"px";
obj.style.top = -(_width-_height)*0.5+"px";
obj.style.left = -(_height-_width)*0.5+"px";
obj.className = className+" "+(_this.option.id+"_screenOrientation");
flag =1 ;
if(_this.option.callback){_this.option.callback();}
}else{
obj.style.width = w_width+"px";
obj.style.height = w_height+"px";
obj.className = className;
obj.style.top = " ";
obj.style.left = " ";
flag = 0;
}
}
function detectOtt(){
_width=(window.innerWidth > 0) ? window.innerWidth : screen.width;
_height=(window.innerHeight > 0) ? window.innerHeight : screen.height;
if(window.orientation==180||window.orientation==0||window.orientation==90||window.orientation==-90){
clearTimeout(timer);
timer = setTimeout(function(){
_this.modifyDetec(_width,_height);
},50);
};
}
if(_this.option.init){_this.option.init();}
detectOtt();
window.addEventListener("resize",detectOtt,false);
};