2013-06-03 9 views
8

Sto creando una galleria di immagini con jquery. C'è qualche possibilità di calcolare se un'immagine è orizzontale o verticale usando jquery?come calcolare se un'immagine è orizzontale o verticale

Grazie per il vostro supporto.

+0

Verificare il rapporto altezza/larghezza? Che cosa hai provato? – JNF

+2

'se larghezza> lunghezza poi paesaggio altro ritratto' –

+0

@Christian Mark Grazie Christian Mark – geovani075

risposta

17

È possibile confrontare semplicemente la larghezza e l'altezza dell'immagine.

var someImg = $("#someId"); 
if (someImg.width() > someImg.height()){ 
    //it's a landscape 
} else if (someImg.width() < someImg.height()){ 
    //it's a portrait 
} else { 
    //image width and height are equal, therefore it is square. 
} 
2

Sotto funzione javascript restituirà l'orientamento più adatto

function get_orientation(src){ 

img = new Image(); 
img.src = src; 
var width = img.width; 
var height = img.height; 
height = height + height // Double the height to get best 
//height = height + (height/2) // Increase height by 50% 

if(width > height) { 
return "landscape"; 
} else { 
return "portrait"; 
} 

} 
+0

Ciò presuppone che l'immagine sia già stata caricata nell'interfaccia utente. Non dovremmo aspettare che l'evento di caricamento dell'immagine si inneschi prima di calcolare effettivamente il rapporto? –

+1

Perché "altezza = altezza + altezza // raddoppia l'altezza per ottenere il massimo"? –

0

Questo ha funzionato per me, utilizzando la naturale altezza/larghezza per ottenere le proprietà originali.

 function imageOrientation(src) { 

      var orientation, 
      img = new Image(); 
      img.src = src; 

      if (img.naturalWidth > img.naturalHeight) { 
       orientation = 'landscape'; 
      } else if (img.naturalWidth < img.naturalHeight) { 
       orientation = 'portrait'; 
      } else { 
       orientation = 'even'; 
      } 

      return orientation; 

     }