Trouvez la hauteur exacte et la largeur de la fenêtre d'une manière cross-browser (pas Prototype / jQuery)

StackOverflow https://stackoverflow.com/questions/1766861

Question

Je suis en train de trouver la hauteur exacte et la largeur de la fenêtre d'un navigateur, mais je soupçonne que ce soit Mozilla ou IE me donne le mauvais numéro. Voici ma méthode pour la taille:

var viewportHeight = window.innerHeight || 
                     document.documentElement.clientHeight || 
                     document.body.clientHeight;

Je ne l'ai pas encore commencé la largeur mais je devine que ça va être quelque chose de similaire.

Y at-il une façon plus correcte d'obtenir ces informations? Idéalement, je voudrais que la solution fonctionne avec Safari / Chrome / autres navigateurs ainsi.

Était-ce utile?

La solution

Vous pouvez essayer ceci:

function getViewport() {

 var viewPortWidth;
 var viewPortHeight;

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 if (typeof window.innerWidth != 'undefined') {
   viewPortWidth = window.innerWidth,
   viewPortHeight = window.innerHeight
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
 && typeof document.documentElement.clientWidth !=
 'undefined' && document.documentElement.clientWidth != 0) {
    viewPortWidth = document.documentElement.clientWidth,
    viewPortHeight = document.documentElement.clientHeight
 }

 // older versions of IE
 else {
   viewPortWidth = document.getElementsByTagName('body')[0].clientWidth,
   viewPortHeight = document.getElementsByTagName('body')[0].clientHeight
 }
 return [viewPortWidth, viewPortHeight];
}

( http://andylangton.co.uk/articles/ javascript / get-viewport taille-javascript / )

Cependant, il est même pas possible d'obtenir les informations viewport dans tous les navigateurs (par exemple IE6 en mode quirks). Mais le scénario ci-dessus devrait faire un bon travail: -)

Autres conseils

Vous pouvez utiliser la version plus courte:

<script type="text/javascript">
<!--
function getViewportSize(){
    var e = window;
    var a = 'inner';
    if (!('innerWidth' in window)){
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] }
}
//-->
</script>

J'ai toujours juste utilisé document.documentElement.clientHeight / clientWidth. Je ne pense pas que vous avez besoin des conditions ou dans ce cas.

Essayer cette ..

<script type="text/javascript">
function ViewPort()
{
var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)
var viewsize = w + "," + h;
alert("Your View Port Size is:" + viewsize);
}
</script>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top