Detectar la orientación de la ventana, si la orientación es Vertical mostrar mensaje de alerta que informa al usuario de las instrucciones


Estoy construyendo un sitio web específicamente para dispositivos móviles. Hay una página en particular que se ve mejor en modo horizontal.

¿Hay alguna forma de detectar si el usuario que visita esa página la está viendo en modo Vertical y, de ser así, mostrar un mensaje informando al usuario de que la página se ve mejor en modo horizontal? Si el usuario ya lo está viendo en modo horizontal, entonces no aparecerá ningún mensaje.

Así que básicamente, quiero que el sitio detecte la orientación de la vista, si la orientación es Vertical , luego muestra un mensaje de alerta que informa al usuario de que esta página se ve mejor en modo Horizontal .

Muchas gracias, Dan

Author: Dan, 2011-02-07

30 answers

if(window.innerHeight > window.innerWidth){
    alert("Please use Landscape!");
}

JQuery Mobile tiene un evento que maneja el cambio de esta propiedad... si desea advertir si alguien gira más tarde - orientationchange

También, después de buscar en Google, echa un vistazo a window.orientation (que creo que se mide en grados...

 223
Author: tobyodavies,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-26 10:44:17

También puedes usar window.matchMedia, que yo uso y prefiero ya que se parece mucho a la sintaxis CSS:

if (window.matchMedia("(orientation: portrait)").matches) {
   // you're in PORTRAIT mode
}

if (window.matchMedia("(orientation: landscape)").matches) {
   // you're in LANDSCAPE mode
}

Probado en iPad 2.

 107
Author: crmpicco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-29 17:08:34

David Walsh tiene un enfoque mejor y directo.

// Listen for orientation changes
window.addEventListener("orientationchange", function() {
  // Announce the new orientation number
  alert(window.orientation);
}, false);

Durante estos cambios, la ventana.la propiedad orientación puede cambiar. Un valor de 0 significa vista vertical, -90 significa que el dispositivo está apaisado hacia la derecha, y 90 significa que el dispositivo está apaisado hacia la izquierda.

Http://davidwalsh.name/orientation-change

 78
Author: Jatin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-31 07:30:34

Puedes usar CSS3:

@media screen and (orientation:landscape)
{
   body
   {
      background: red;
   }
}
 33
Author: Thomas Decaux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-26 08:39:46

Hay algunas maneras de hacerlo, por ejemplo:

  • Comprobar window.orientation valor
  • Compare innerHeight vs. innerWidth

Puede adaptar uno de los métodos a continuación.


Compruebe si el dispositivo está en modo vertical

function isPortrait() {
    return window.innerHeight > window.innerWidth;
}

Compruebe si el dispositivo está en modo horizontal

function isLandscape() {
    return (window.orientation === 90 || window.orientation === -90);
}

Ejemplo de uso

if (isPortrait()) {
    alert("This page is best viewed in landscape mode");
}

¿Cómo detecto el cambio de orientación?

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});
 16
Author: martynas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-12 01:06:10

Creo que la solución más estable es usar la pantalla en lugar de la ventana, porque podría ser tanto horizontal como vertical si va a cambiar el tamaño de la ventana del navegador en la computadora de escritorio.

if (screen.height > screen.width){
    alert("Please use Landscape!");
}
 10
Author: artnikpro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-19 10:38:42

Con el fin de aplicar todos estos grandes comentarios a mi codificación diaria, para la continuidad entre todas mis aplicaciones, he decidido utilizar lo siguiente tanto en mi código jquery y jquery mobile.

window.onresize = function (event) {
  applyOrientation();
}

function applyOrientation() {
  if (window.innerHeight > window.innerWidth) {
    alert("You are now in portrait");
  } else {
    alert("You are now in landscape");
  }
}
 8
Author: dLindley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-29 13:27:44

No intentes con la ventana fija.consultas de orientación (0, 90, etc. no significa retrato, paisaje, etc.):

Http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/

Incluso en iOS7 dependiendo de cómo entres en el navegador 0 no siempre es retrato

 6
Author: kev666n,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-13 16:08:35

Después de un poco de experimentación he encontrado que la rotación de un dispositivo consciente de orientación siempre activará el evento resize de una ventana del navegador. Así que en su controlador de redimensionamiento simplemente llame a una función como:

function is_landscape() {
  return (window.innerWidth > window.innerHeight);
}
 5
Author: Dave Sag,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-03 22:19:22

Combiné dos soluciones y funciona bien para mí.

window.addEventListener("orientationchange", function() {                   
    if (window.matchMedia("(orientation: portrait)").matches) {
       alert("PORTRAIT")
     }
    if (window.matchMedia("(orientation: landscape)").matches) {
      alert("LANSCAPE")
     }
}, false);
 5
Author: ARTniyet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-20 09:15:22

Obtenga la orientación (en cualquier momento en su código js) a través de

window.orientation

Cuando window.orientation devuelve 0 o 180entonces estás en modo vertical, cuando devuelves 90 o 270entonces estás en modo horizontal.

 4
Author: Sliq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-11 13:09:48

No estoy de acuerdo con la respuesta más votada. Use screen y no window

    if(screen.innerHeight > screen.innerWidth){
    alert("Please use Landscape!");
}

Es la forma correcta de hacerlo. Si calculas con window.height, tendrás problemas en Android. Cuando el teclado está abierto, la ventana se encoge. Así que usa pantalla en lugar de ventana.

El screen.orientation.type es una buena respuesta pero con IE. https://caniuse.com/#search=screen.orientation

 3
Author: Stefdelec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-31 07:05:26
//see also http://stackoverflow.com/questions/641857/javascript-window-resize-event
//see also http://mbccs.blogspot.com/2007/11/fixing-window-resize-event-in-ie.html
/*
Be wary of this:
While you can just hook up to the standard window resize event, you'll find that in IE, the event is fired once for every X and once for every Y axis movement, resulting in a ton of events being fired which might have a performance impact on your site if rendering is an intensive task.
*/

//setup 
window.onresize = function(event) {
    window_resize(event);
}

//timeout wrapper points with doResizeCode as callback
function window_resize(e) { 
     window.clearTimeout(resizeTimeoutId); 
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10); 
}

//wrapper for height/width check
function doResizeCode() {
    if(window.innerHeight > window.innerWidth){
        alert("Please view in landscape");
    }
}
 2
Author: Adolph Trudeau,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-02-07 18:35:34

Otra alternativa para determinar la orientación, basada en la comparación de la anchura / altura:

var mql = window.matchMedia("(min-aspect-ratio: 4/3)");
if (mql.matches) {
     orientation = 'landscape';
} 

Se usa en el evento "redimensionar":

window.addEventListener("resize", function() { ... });
 2
Author: Gregor Srdic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-16 14:14:09

IOS no actualizar screen.width & screen.height cuando la orientación cambia. Android no actualiza window.orientation cuando cambia.

Mi solución a este problema:

var isAndroid = /(android)/i.test(navigator.userAgent);

if(isAndroid)
{
    if(screen.width < screen.height){
        //portrait mode on Android
    }
} else {
    if(window.orientation == 0){
        //portrait mode iOS and other devices
    }
}

Puede detectar este cambio en la orientación tanto en Android como en iOS con el siguiente código:

var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert("the orientation has changed");
}, false);

Si el evento onorientationchange no está soportado, el evento enlazado será el evento resize.

 2
Author: Sandman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 12:04:03
$(window).on("orientationchange",function( event ){
    alert(screen.orientation.type)
});
 2
Author: Jomin George Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-18 13:58:41

Gracias a tobyodavies por guiar el camino.

Para lograr un mensaje de alerta basado en la orientación del dispositivo móvil, debe implementar el siguiente script dentro del function setHeight() {

if(window.innerHeight > window.innerWidth){
    alert("Please view in landscape");
}
 1
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-05 08:18:55

En lugar de 270, puede ser -90 (menos 90).

 1
Author: zeuf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-14 17:09:22

Esto se expande en una respuesta anterior. La mejor solución que he encontrado es hacer un atributo CSS inocuo que solo aparece si se cumple una consulta de medios CSS3, y luego tener la prueba JS para ese atributo.

Así que, por ejemplo, en el CSS tendrías:

@media screen only and (orientation:landscape)
{
    //  Some innocuous rule here
    body
    {
        background-color: #fffffe;
    }
}
@media screen only and (orientation:portrait)
{
    //  Some innocuous rule here
    body
    {
        background-color: #fffeff;
    }
}

Luego vas a JavaScript (estoy usando jQuery para funsies). Las declaraciones de color pueden ser extrañas, por lo que es posible que desee usar otra cosa, pero este es el método más infalible que he encontrado para probarlo. A continuación, puede utilizar el cambiar el tamaño del evento para recoger en el cambio. Ponlo todo junto para:

function detectOrientation(){
    //  Referencing the CSS rules here.
    //  Change your attributes and values to match what you have set up.
    var bodyColor = $("body").css("background-color");
    if (bodyColor == "#fffffe") {
        return "landscape";
    } else
    if (bodyColor == "#fffeff") {
        return "portrait";
    }
}
$(document).ready(function(){
    var orientation = detectOrientation();
    alert("Your orientation is " + orientation + "!");
    $(document).resize(function(){
        orientation = detectOrientation();
        alert("Your orientation is " + orientation + "!");
    });
});

La mejor parte de esto es que al escribir esta respuesta, no parece tener ningún efecto en las interfaces de escritorio, ya que (generalmente) no (parecen) pasar ningún argumento de orientación a la página.

 1
Author: Josh C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-30 14:01:35

Este es el mejor método que encontré, basado en el artículo de David Walsh (Detectar Cambios de orientación en Dispositivos Móviles)

if ( window.matchMedia("(orientation: portrait)").matches ) {  
   alert("Please use Landscape!") 
}

Explicación:

Ventana.matchMedia () es un método nativo que le permite definir una regla de consulta de medios y verificar su validez en cualquier momento.

Me parece útil adjuntar un receptor onchange en el valor devuelto de este método. Ejemplo:

var mediaQueryRule = window.matchMedia("(orientation: portrait)")
mediaQueryRule.onchange = function(){ alert("screen orientation changed") }
 1
Author: Shibl,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-11 05:45:50

Usé para Android Chrome "La API de orientación de pantalla"

Para buscar la consola de llamada de orientación actual.log (screen.orientación.type) (y tal vez screen.orientación.Angulo).

Resultados: portrait-primary | portrait-secondary | landscape-primary / landscape-secondary

A continuación está mi código, espero que sea útil:

var m_isOrientation = ("orientation" in screen) && (typeof screen.orientation.lock == 'function') && (typeof screen.orientation.unlock == 'function');
...
if (!isFullscreen()) return;
screen.orientation.lock('landscape-secondary').then(
    function() {
        console.log('new orientation is landscape-secondary');
    },
    function(e) {
        console.error(e);
    }
);//here's Promise
...
screen.orientation.unlock();
  • He probado solo para Android Chrome-ok
 1
Author: Dmitry Sokolyuk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-09 13:11:06
screen.orientation.addEventListener("change", function(e) {
 console.log(screen.orientation.type + " " + screen.orientation.angle);
}, false);
 1
Author: zloctb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-04 19:12:18

El objeto window en JavaScript en dispositivos iOS tiene una propiedad orientation que se puede usar para determinar la rotación del dispositivo. A continuación se muestra la ventana valores.orientación para dispositivos iOS (por ejemplo, iPhone, iPad, iPod) en diferentes orientaciones.

Esta solución también funciona para dispositivos Android. Me registré en el navegador nativo de Android (navegador de Internet) y en el navegador Chrome, incluso en las versiones anteriores de la misma.

function readDeviceOrientation() {                      
    if (Math.abs(window.orientation) === 90) {
        // Landscape
    } else {
        // Portrait
    }
}
 1
Author: Dmytro Medvid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-13 11:59:13

CCS solamente

@media (max-width: 1024px) and (orientation: portrait){ /* tablet and smaller */
  body:after{
    position: absolute;
    z-index: 9999;
    width: 100%;
    top: 0;
    bottom: 0;
    content: "";
    background: #212121 url(http://i.stack.imgur.com/sValK.png) 0 0 no-repeat; /* replace with an image that tells the visitor to rotate the device to landscape mode */
    background-size: 100% auto;
    opacity: 0.95;
  }
}

En algunos casos, es posible que desee agregar un pequeño fragmento de código para recargar a la página después de que el visitante rote el dispositivo, de modo que el CSS se renderice correctamente:

window.onorientationchange = function() { 
    var orientation = window.orientation; 
        switch(orientation) { 
            case 0:
            case 90:
            case -90: window.location.reload(); 
            break; } 
};
 1
Author: cptstarling,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-22 12:57:33

Esto es lo que uso.

function getOrientation() {

    // if window.orientation is available...
    if( window.orientation && typeof window.orientation === 'number' ) {

        // ... and if the absolute value of orientation is 90...
        if( Math.abs( window.orientation ) == 90 ) {

              // ... then it's landscape
              return 'landscape';

        } else {

              // ... otherwise it's portrait
              return 'portrait';

        }

    } else {

        return false; // window.orientation not available

    }

}

Aplicación

window.addEventListener("orientationchange", function() {

     // if orientation is landscape...
     if( getOrientation() === 'landscape' ) {

         // ...do your thing

    }

}, false);
 1
Author: CTE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-06 16:32:35
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Rotation Test</title>
  <link type="text/css" href="css/style.css" rel="stylesheet"></style>
  <script src="js/jquery-1.5.min.js" type="text/javascript"></script>
  <script type="text/javascript">
        window.addEventListener("resize", function() {
            // Get screen size (inner/outerWidth, inner/outerHeight)
            var height = $(window).height();
            var width = $(window).width();

            if(width>height) {
              // Landscape
              $("#mode").text("LANDSCAPE");
            } else {
              // Portrait
              $("#mode").text("PORTRAIT");
            }
        }, false);

  </script>
 </head>
 <body onorientationchange="updateOrientation();">
   <div id="mode">LANDSCAPE</div>
 </body>
</html>
 0
Author: Gaurav kumar MVC Expert,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-08 14:10:56

Hay una manera por la cual puede detectar si el usuario volteó su dispositivo al modo retrato usando screen.orientation

Simplemente use el siguiente código:

screen.orientation.onchange = function () {
     var type = screen.orientation.type;
     if (type.match(/portrait/)) {
         alert('Please flip to landscape, to use this app!');
     }
}

Ahora, onchange se disparará cuando el usuario voltee el dispositivo y la alerta aparecerá cuando el usuario use el modo retrato.

 0
Author: nmnsud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-30 18:40:31

Una cosa a tener en cuenta sobre window.orientation es que volverá undefined si no está en un dispositivo móvil. Así que una buena función para comprobar la orientación podría verse así, donde x es window.orientation:

//check for orientation
function getOrientation(x){
  if (x===undefined){
    return 'desktop'
  } else {
    var y;
    x < 0 ? y = 'landscape' : y = 'portrait';
    return y;
  }
}

Llámalo así:

var o = getOrientation(window.orientation);
window.addEventListener("orientationchange", function() {
  o = getOrientation(window.orientation);
  console.log(o);
}, false);
 0
Author: Harry Stevens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-19 12:05:22

O simplemente podrías usar esto..

window.addEventListener("orientationchange", function() {
    if (window.orientation == "90" || window.orientation == "-90") {
        //Do stuff
    }
}, false);
 0
Author: Brad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-04 00:44:05

Si tiene los navegadores más recientes, window.orientation podría no funcionar. En ese caso, utilice el siguiente código para obtener angle -

var orientation = window.screen.orientation.angle;

Esta sigue siendo una tecnología experimental, puede comprobar la compatibilidad del navegador aquí

 0
Author: Atul Kumar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-31 10:38:39