获得窗口属性

查看滚动条的滚动距离

window.pageYOffset

window.pageXOffset

IE8和IE8以下不兼容

对于IE8以及IE8以下的浏览器使用:

document.body.scorllLeftTop 

document.documentElement.scorllLeft/Top

兼容性比较混,用的时候取两个值相加,因为不可能存在两个同时有值

封装一个兼容所有浏览器的取窗口页面尺寸的函数

function getScrollOffset() {
	if(window.pageXOffset) {
		return {
			x : window.pageXOffset,
			y : window.pageYOffset
		}
	}else {
		return {
			x : document.body.scrollLeft + document.documentElement.scrollLeft,
			y : document.body.scrollTop + document.documentElement.scrollTop
		}
	}
}

查看页面可视区窗口的尺寸

window.innerWidth

window.innerHeight

IE8和IE8以下不兼容

document.documentElement.clientWidth

document.documentElement.clientHeight

标准模式下,所有浏览器都兼容

document.body.clientWidth

document.body.clientHeight

使用于怪异模式下的浏览器

封装以下使用所有浏览器的可视区函数

function getViewportOffset() {
	if(window.innerHeight) {
		return {
			w : window.innerWidth,
			h : window.innerHeight
		}
	}else if(document.compatMode === 'BackCompat') {
		return {
			w : document.body.clienWidth,
			h : document.body.clientHeight
		}
	}else {
		return {
			w : document.documentElement.clienWidth,
			h : document.documentElement.clientHeight
		}
	}
}

查看元素的几何尺寸

domEle.getBoundingClientRect();

兼容性很好

该方法返回一个对象,对象里面有left,top,right,bottom等属性。lefi和top代表该元素左上角的x和y坐标,right和bottom代表右下角的x和y坐标

在IE里面height和width属性没有

返回的结果并不是‘实时的’

查看元素尺寸

dom.offsetWidth,dom.offsetHeight

求的是视觉上的尺寸,不会包含maring

查看元素位置:

dom.offsetLeft

dom.offsetTop

对于无定位父级的元素,返回相对于文档的坐标;对于有定位父级的元素,返回相对于最近的有定位的父级的坐标

看下面的情况:

210 = 200 + 2 + 8 

纵向的margin塌陷掉了

dom.offsetParent

返回最近的有定位的父级,若无,返回body,body.offsetParent返回null

让滚动条滚动

window上有三个方法

scroll(),scrollTo()        scrollBy();

三个方法功能类似,用法都是将x,y坐标传入。即实现让滚动轮滚动到当前位置

区别:scrollBy()会在之前的数据基础之上做累加。

现在做一个自动阅读的功能

 <div style="width: 100px;height: 100px;background-color: red;color: #FFF;font-size: 20px;font-weight: bold;text-align: center;line-height: 100px;position: fixed;bottom: 200px;right: 50px;border-radius: 50%;opacity: 0.5;">start</div>
  <div style="width: 100px;height: 100px;background-color: green;color: #FFF;font-size: 20px;font-weight: bold;text-align: center;line-height: 100px;position: fixed;bottom: 90px;right: 50px;border-radius: 50%;opacity: 0.5;">stop</div>

两个div上面是文本

猜你喜欢

转载自blog.csdn.net/VVVZCS/article/details/82148782