今天来讲一下dom 的元素大小和元素偏移。
一共要讲这几个方面:
offsetWidth, offsetHeight, offsetLeft, offsetTop
首先来看一下这个例子:
做一个定时器,每隔50秒自动增加3个像素的宽度。
var box =document. getElementById ("box ");
setInterval (function (){
box. style. width =parseInt (box. offsetWidth) +3+“px ”;
},50)
这里要讲一下,offsetWidth 是一个带单位的取值方式,但是它只能取值不能随意修改其大小。在运用定时器去设定这些大小时,要先去单位的同时取整,再添加单位进行灵活设置。要获取一个变动的数值,在这里需要用dom. style. 元素样式来获取,需要提醒的是,边框大小、内边距也算在长度单位里面,而外边距只能用于定位当中。
#box1{width: 300px; height: 300px; background -color: red; margin: 50px; position: relative; }
#box2{width: 80px; height: 80px; background -color: blue; position: absolute; left: 100px; top: 100px; }
所以里面的盒子之于外面的盒子可以用offsetLeft 、offsetTop 来获取。如果只有一个盒子且有定位的话,那么是之于网页的距离。
像这里的话,里面的盒子,offsetLeft: 100px, offsetTop: 100px, 外面的盒子,offsetLeft: 50px, offsetTop: 50px.
像上节课讲到的非IE 浏览器和IE 8及以下的浏览器用来获取样式的值时,讲到了
dom. getComputedStyle (dom, null )[“元素样式”]以及dom. getCurrentStyle [“元素样式”]这两种写法,获取到的值是不带单位的,比如宽度为300,高度为300,左边距为100,上边距为100。
所以,综上所述,offsetWidth、offsetHeight可以取到dom元素的大小,而offsetTop、offsetLeft等只能取到dom元素偏移量的大小。