如何根据设备方向调用两个HTML文件

时间:2012-11-09 06:58:26

标签: javascript html ipad

我从JavaScript函数调用两个HTML文件我希望当iPad处于纵向模式时它应该加载portrati.html并且在景观模式下它应该打开ladnscape.html

使用以下代码,当我们第一次加载时,它可以在浏览器上运行,但是当我们更改方向时,它不会更改文件。

<SCRIPT language="JavaScript">
 if(window.innerHeight < window.innerWidth){
    window.location="Landscape/index.html";
} 
else if (window.innerHeight > window.innerWidth){
    window.location="Potrait/index.html";
}
</SCRIPT>

1 个答案:

答案 0 :(得分:1)

iOS上的Safari有一个事件:

window.onorientationchange

您可以使用它来检测更改。

window.onorientationchange = function() {
    switch (window.orientation) {
        case 0: // portrait
            window.location = "Portrait/index.html";
            break;
        case 90: // Landscape
            window.location = "Landscape/index.html";
            break;
        case -90: // Other way round
            window.location = "OtherLandscape/index.html";
            break;
    }
}

此操作仅在iOS 4开始运行。如果您使用的是旧版本,则应使用onresize-Event:

window.onresize = function() {
     if(window.innerHeight < window.innerWidth){
         window.location="Landscape/index.html";
     } 
     else if (window.innerHeight > window.innerWidth){
         window.location="Potrait/index.html";
     }
}

代码的Copy-Pasta。