js可以设置网页默认为横屏状态吗?js设置网页横屏和竖屏切换

摘要:打开页面时通过 window.orientation 可以判断网页是横屏还是竖屏,如果是竖屏,给整个页面添加样式 transform: rotate(90deg); 这样,你的页面就显示横屏的效果了。 总的来说,结合window.orientationchange和window.orientation可以灵活的对网页进行变换。

首先,横竖屏状态是无法用程序控制的,但是,解决方案还是有的:

打开页面时通过 window.orientation 可以判断网页是横屏还是竖屏,如果是竖屏,给整个页面添加样式 transform: rotate(90deg); 这样,你的页面就显示横屏的效果了。

用户看到横屏效果,第一反应是旋转手机,这个时候你可以通过window.orientationchange来捕获这个事件,然后再把transform的rotate变回0即可。 总的来说,结合window.orientationchange和window.orientation可以灵活的对网页进行变换。


window.orientation判断,然后提示用户进行旋转

if(window.orientation==90||window.orientation==-90){
    alert("横屏状态!")
}


或者监听旋转事件

window.onorientationchange = function(){ 
    switch(window.orientation){ 
        case -90: 
        case 90: 
            alert("横屏:" + window.orientation);
        case 0: 
        case 180: 
             alert("竖屏:" + window.orientation);
        break; 
    } 
} 


css的媒介查询也是能判断的

@media (orientation: portrait) { } 横屏 @media (orientation: landscape) { }竖屏 


不过还是有解决方案的:
打开页面时通过window.orientation可以判断网页是横屏还是竖屏,如果是竖屏,给整个页面添加样式

transform: rotate(90deg);

这样,你的页面就显示横屏的效果了。


或者其他实现方法:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="application/xhtml+xml;charset=UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>手机横、竖屏事件</title>
<script language="javascript" type="text/javascript">
//屏幕方向标识,0横屏,其他值竖屏
var orientation=0;
//转屏事件,内部功能可以自定义
function screenOrientationEvent(){
    if(orientation == 0)document.getElementById("change").value="竖";
    else document.getElementById("change").value="横";
}
var innerWidthTmp = window.innerWidth;
//横竖屏事件监听方法
function screenOrientationListener(){
    try{
        var iw = window.innerWidth;    
        //屏幕方向改变处理
        if(iw != innerWidthTmp){
            if(iw>window.innerHeight)orientation = 90;
            else orientation = 0;
            //调用转屏事件
            screenOrientationEvent();
            innerWidthTmp = iw;
        }
    } catch(e){alert(e);};
    //间隔固定事件检查是否转屏,默认500毫秒
    setTimeout("screenOrientationListener()",500);
}
//启动横竖屏事件监听
screenOrientationListener();
</script>
</head>
<body onload="screenOrientationEvent()">
<input id="change" type="text" value=""/>
</body>
</html>


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_331