需要獲取一些HTML的對象的坐標來更靈活的設置目標層的坐標,這裡可以通過用到document.body.scrollTop等屬性,但是這些屬性在xhtml的標準網頁中或更簡單的說就是帶<!DOCTYPE...>的標籤中得到的值是0;如果不要此標籤則一切正常,那麼在xhtml中如何獲取body的坐標呢?當然有辦法了,我們使用document.documentElement來取代document.body例如可以這樣寫:
複製代碼代碼如下:
var top=document.documentElement.scrollTop ||document.body.scroolTop;
js中的||是個好東西,不但可以用在if的條件語句中,而且還可以用在變量的賦值上,上例可以寫成如下格式:
複製代碼代碼如下:
var top=document.documentElement.scrollTop ?document.documentElement.scrollTop : document.body.scrollTop;
這樣寫可以有很好的兼容性。還要注意的一點是:如果不聲明document.documentElement.scrollTop的值反而會顯示0。
說明要想獲取當前頁面上滾動條坐標的縱坐標位置:用
document.documentElement.scrollTop而不是用
document.body.scrollTop;
document.documentElement獲取的是html標籤,
document.body獲取的是body標籤;
在標準w3c下,document.body.scrollTop恆為0,需要用document.documentElement.scrollTop來代替;
如果我們要定位鼠標相對於頁面的絕度位置時,會在搜索引擎中得到的大多會讓你用
event.clientX+document.body.scrollLeft ,event.clientY+document.body.scrollTop;
如果發現鼠標偏離了你的想像,一點都奇怪,因為IE5.5之後就不在支持document.body.scrollX對象了
所以我們要加上一句;
複製代碼代碼如下:
if (document.body && document.body.scrollTop &&document.body.scrollLeft)
{
top=document.body.scrollTop;
left=document.body.scrollleft;
}
if (document.documentElement && document.documentElement.scrollTop&& document.documentElement.scrollLeft)
{
top=document.documentElement.scrollTop;
left=document.documentElement.scrollLeft;
}
下面介紹一些參數的用法:
網頁的可見區域寬度:document.body.clientWidth;
網頁的可見區域高度:document.body.clientHeight;
網頁可見區域寬:document.body.offsetWidth;(包括邊線的寬);
網頁可見區域高:document.body.offsetHeight;(包括邊線的寬);
網頁正文全文寬:document.body.scrollWidth;
網頁正文全文高:document.body.scrollHeight;
網頁被捲去的高:document.body.scrollTop;
網頁被捲去的左:document.body.scrollLeft;
網頁正文部分上:windows.screenTop;
網頁正文部分左:windows.screenLeft;
屏幕分辨率的高:windows.screen.height;
屏幕分辨率的寬:windows.screen.widht;
屏幕可用工作區高度:windows.screen.availHeight;
屏幕可用工作區寬度:windows.screen.availWidth;
獲取對象的滾動高度:scrollHeight;
設置或獲取位於對象左邊界和窗口中目前可見內容的最左端之間的距離:scrollLeft;
設置或獲取位於對象最頂端和窗口中可見內容的最頂端之間的距離:scrollTop;
獲取對象的滾動寬度:scrollWidth;
獲取對象相對於版面或由父坐標:offsetParent 屬性指定的父坐標的高度:offsetHeight;
獲取對象相對於版面或由offsetParent 屬性指定的父坐標的計算左側位置:offsetLeft;
獲取對象相對於版面或由offsetTop 屬性指定的父坐標的計算頂端位置:offsetTop;
event.clientX:相對於文檔的水平坐標;
event.clientY:相對於文檔的垂直坐標;
event.offsetX:相對於容器的水平坐標;
event.offsetY:相對於容器的垂直坐標;
document.documentElement.scrollTop:設置滾動的垂直高度
event.clientX + document.documentElement.scrollTop:相對文檔的水平位置+垂直方向的滾動量;