Maison > interface Web > js tutoriel > le corps du texte

js获取浏览器高度 窗口高度 元素尺寸 偏移属性的方法

高洛峰
Libérer: 2016-12-06 11:44:14
original
1823 Les gens l'ont consulté

如下所示:

screen.width
screen.height
 
 
screen.availHeight //获取去除状态栏后的屏幕高度
screen.availWidth //获取去除状态栏后的屏幕高度
Copier après la connexion

一、通过浏览器获得屏幕的尺寸

二、获取浏览器窗口内容的尺寸

//高度
window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
 
//宽度
window.innerWidth || document.documentElement.clientWidth || document.body.clientWidht
 
/ *
 * window.innerHeight  FF/CH 支持,获取窗口尺寸。
 * document.documentElement.clientHeight  IE/CH支持
 * document.body.client  通过body元素获取内容的尺寸
 
* /
Copier après la connexion

三、滚动条支持的差异性

不进行任何滚动条更改的页面,Firefox/IE 默认认为HTML元素具有滚动条属性。而body不具有。

但Chrome 则认为body是具有滚动条属性的。

因此兼容性的写法是:

   
document.documentElement.scrollTop || document.body.scrollTop
Copier après la connexion

四、获取元素的尺寸

elemnt.offsetWidth
elemnt.offsetHeight
 
// 仅IE5不支持,放心使用吧
Copier après la connexion

* offsetWidth 可以获取元素的高度尺寸,包括:width + padding[left,right] + border[left,right]

* offsetHeight 可以获取元素的宽度尺寸,包括:height + padding[top,bottom] + bottom[top,bottom]

五、元素的偏移属性

element.offsetTop //获取元素与其偏移参考父元素顶部的间隔距离
element.offsetLeft //获取元素与其偏移参考父元素左边的间隔距离
element.offsetParent //获取当前元素的参考父元素
Copier après la connexion

*offsetTop 可以获取元素距其上一级的偏移参考父元素顶部的距离。包括:margin[top] + top

*offsetLeft 可以获取元素距其上一级的偏移参考父元素左边的距离。包括:margin[left] + left

*注意的是offsetParent在IE6/7,与IE8/FF/CH中存在兼容性问题:

在FF/Chrome/IE8+ :

如果当前元素有定位,则偏移参考父元素是其上一级的最近的那个定位元素。

如果当前元素没有定位,则默认以body为最终的参考父元素。

在IE6/7:

不论有没有定位,其偏移参考父元素都是其上一级的父元素。

总的来说:

不论是FF/Chrome还是IE,最终的参考父元素都是body元素, 因此兼容的方法就是获取当前元素到body元素的偏移位置值。

兼容性写法

function getOffestValue(elem){
 
    var Far = null;
    var topValue = elem.offsetTop;
    var leftValue = elem.offsetLeft;
    var offsetFar = elem.offsetParent;
 
    while(offsetFar){
      alert(offsetFar.tagName)
      topValue += offsetFar.offsetTop;
      leftValue += offsetFar.offsetLeft;
      Far = offsetFar;
      offsetFar = offsetFar.offsetParent;
    }
    return {'top':topValue,'left':leftValue,'Far':Far}
  }
 
/*
 * top 当前元素距离body元素顶部的距离。
 * left 当前元素距离body元素左侧的距离。
 * Far 返回最终的参考父元素。
*/
Copier après la connexion

   


Étiquettes associées:
js
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!