Running Javascript every X seconds - what's wrong with this code?

时间:2015-06-25 19:04:20

标签: javascript function rotation alert

I am using this code to detect when the device is in landscape but it doesn't work. Any ideas? function OrientationAlert { if(window.innerHeight < window.innerWidth){ alert("Please rotate your device and view this in portrait orientation."); } setInterval(OrientationAlert, 5000); }

4 个答案:

答案 0 :(得分:1)

function OrientationAlert(){
if(window.innerWidth < 500){
    setInterval(function(){
    if(window.innerHeight < window.innerWidth){
        alert("Please rotate your device and view this in portrait orientation.");
       }
    }, 5000);
    }
}
    <!DOCTYPE html>
    <html>
    <body onload="OrientationAlert()">
    </body>
    </html>

尝试一下!!

更新: - 根据您在评论

中提到的要求添加条件
 if(window.innerWidth < 500) {
//the setInterval() funcion is registered at the time of page or else it wont
    }

答案 1 :(得分:0)

Try setInterval(function(){ if(window.innerHeight < window.innerWidth){ alert("Please rotate your device and view this in portrait orientation."); } }, 3000);

答案 2 :(得分:0)

您也可以使用orientationchange事件。 这是一个例子:

function doOnOrientationChange() {
    switch(window.orientation)
    {
        case -90:
        case 90:
            alert('landscape');
            break;
        default:
            alert('portrait');
            break;
    }
}

window.addEventListener('orientationchange', doOnOrientationChange);

// Initial execution if needed
doOnOrientationChange();

浏览器支持不是太糟糕,因为它只会发挥移动设备的作用,它可能是你的选择。以下是我可以使用Link的内容。

您可以在此处找到有关

的更多信息

Screen Orientation API

您也可以在回调函数中声明它,如下所示:

window.addEventListener('orientationchange', function() {
    switch(window.orientation)
    {
        case -90:
        case 90:
            alert('landscape');
            break;
        default:
            alert('portrait');
            break;
    }
});

希望有所帮助。

答案 3 :(得分:0)

var a = OrientationAlert {...}
setInterval(a,5000);