HTML元素坐标和尺寸

文档坐标和视口坐标

文档坐标是指网页从<html>开始至</html>结束之间的宽高,窗口坐标是指浏览器除去菜单栏、书签栏、滚动条之后剩下的视野宽高。

获取代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//文档坐标
function getDocument() {
var documentWidth = document.documentElement.offsetWidth;
var documentHeight = document.documentElement.offsetHeight;
return {w: documentWidth, h: documentHeight}
}

//视口坐标
function getViewport(w) {
//使用指定的窗口,若不带参数则使用当前窗口
w = w || window;
//除了IE8及更早的版本以外,其他浏览器都能用
if(w.innerWidth != null) {
return {w: w.innerWidth, h: w.innerHeight}
}
//对标准模式下的IE
var d = w.document;
if(document.compatMode == "CSS1Compat") {
return {w: d.documentElement.clientWidth, h: d.documentElement.clientHeight};
}
//对怪异模式下的浏览器
return {w: d.body.clientWidth, h: d.body.clientHeight};
}

滚动条滚动位置坐标

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
function getScroll(w) {
w = w || window;
//除了IE 8以及更早的版本以外,其他浏览器都支持
if(w.pageXOffset != null) {
return {w: w.pageXOffset, h: w.pageYOffset}
}
//标准模式下的IE
var d = w.document;
if(document.compatMode == "CSS1Compat")
return {x: d.documentElement.scrollLeft, y: d.documentElement.scrollTop};
//对怪异模式下的浏览器
return { x: d.body.scrollLeft, y: d.body.scrollTop};
}

查询元素尺寸和位置

判定一个元素的尺寸和位置最简单的方法就是调用它的getBoundingClientRect()方法,这个方法返回元素在视口坐标中的位置

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getElementRect(e){
var box = e.getBoundingClientRect();
var x = box.left;
var y = box.top;
return {x:x, y: y};
}
var h2 = document.getElementsByTagName("h2")[0];
getElementRect(h2);

//在很多浏览器里,getBoundingClientRect()还包括元素宽高属性,但在原始的IE中未实现,不过我们可以这样写:
function getElementRect(e) {
var box = e.getBoundingClientRect();
var w = box.width || box.right - box.left;
var h = box.height || box.bottom - box.top;
return {w: w, h: h};
}

元素滚动

使用window.scrollTo()方法可以滚动到页面的任何位置

1
2
3
4
5
6
7
//滚动到页面底部
function scrollBottom(){
//获取文档和视口的高度
var documentHeight = document.documentElement.offsetHeight;
var viewportHeight = window.innerHeight;
window.scrollTo(0, documentHeight - viewportHeight);
}