做论坛网站的应用,学建设网站,wordpress卡死了,深圳企业网站建设服务1、获取网页元素的相对位置的普通方法
有了绝对位置以后#xff0c;获得相对位置就很容易了#xff0c;只要将绝对坐标减去页面的滚动条滚动的距离就可以了。滚动条滚动的垂直距离#xff0c;是document对象的scrollTop属性#xff1b;滚动条滚动的水平距离是document对象…1、获取网页元素的相对位置的普通方法
有了绝对位置以后获得相对位置就很容易了只要将绝对坐标减去页面的滚动条滚动的距离就可以了。滚动条滚动的垂直距离是document对象的scrollTop属性滚动条滚动的水平距离是document对象的scrollLeft属性。 scrollTop和scrollLeft属性是可以赋值的并且会立即自动滚动网页到相应位置因此可以利用它们改变网页元素的相对位置。 另外element.scrollIntoView()方法也有类似作用可以使网页元素出现在浏览器窗口的左上角。 // 获取leftfunction getElementViewLeft(element){var actualLeft element.offsetLeft;var current element.offsetParent;while (current ! null){actualLeft current.offsetLeft;current current.offsetParent;}if (document.compatMode BackCompat){var elementScrollLeft document.body.scrollLeft;} else {var elementScrollLeft document.documentElement.scrollLeft; }return actualLeft - elementScrollLeft;} // 获取topfunction getElementViewTop(element){var actualTop element.offsetTop;var current element.offsetParent;while (current ! null){actualTop current. offsetTop;current current.offsetParent;}if (document.compatMode BackCompat){var elementScrollTop document.body.scrollTop;} else {var elementScrollTop document.documentElement.scrollTop; }return actualTop - elementScrollTop;} 2、获取元素位置的快速方法
使用getBoundingClientRect()方法。它返回一个对象其中包含了left、right、top、bottom四个属性分别对应了该元素的左上角和右下角相对于浏览器窗口viewport左上角的距离。
所以网页元素的相对位置就是
var X this.getBoundingClientRect().left;var Y this.getBoundingClientRect().top;
再加上滚动距离就可以得到绝对位置
var X this.getBoundingClientRect().left document.documentElement.scrollLeft;var Y this.getBoundingClientRect().top document.documentElement.scrollTop;
目前IE、Firefox 3.0、Opera 9.5都支持该方法而Firefox 2.x、Safari、Chrome、Konqueror不支持。