DIV CSS 佈局教程網

JavaScript 定位詳解:offset、screen、scroll、client 全對比
編輯:關於JavaScript     

在處理元素定位與鼠標坐標時,JavaScript 提供了一系列容易混淆的屬性。理清 offset、screen、scroll、client 這幾組屬性的含義,是精確控制佈局與交互的基礎。

核心屬性速查

  • obj.offset[Width|Height|Top|Left]:元素相對於父元素的位置與尺寸
  • event.offset[X|Y]:鼠標相對於觸發事件的元素的位置
  • event.screen[X|Y]:鼠標相對於屏幕的坐標
  • event.client[X|Y]:鼠標相對於網頁(視窗)的坐標
  • obj.scroll[Width|Height|Top|Left]:元素滾動的尺寸與位置
  • obj.client[Width|Height|Top|Left]:元素可見區域的尺寸

完整測試代碼

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div{ font-family:"宋體"; font-size:12px; color:#000; }
#div1{ position:absolute; background:#f0f0f0; width:200px; height:200px; left:20px; top:0; z-index:1; }
#div2{ background:#cfc0cf; width:200px; height:210px; position:absolute; left:261px; top:347px; z-index:100; }
#div3{ background:#abbfbf; width:200px; height:200px; position:absolute; left:20px; top:247px; z-index:100; }
#div4{ background:#cfcfcf; width:200px; height:200px; position:absolute; left:461px; top:147px; z-index:100; }
</style>
</head>
<body>
<div id='div1' onclick='eventc(this)'></div>
<div id='div2' onclick='client(this);'></div>
<div id='div3' onclick='screen(this);'></div>
<div id='div4' onclick='offset(this);'>offset 元素相對於父窗體的位置</div>
<script>
function offset(ids){
  ids.innerHTML = "offsetLeft =" + ids.offsetLeft + "<BR>";
  ids.innerHTML += "offsetWidth =" + ids.offsetWidth + "<BR>";
  ids.innerHTML += "offsetHeight =" + ids.offsetHeight + "<BR>";
  ids.innerHTML += "offsetTop =" + ids.offsetTop + "<BR>";
  ids.innerHTML += "event.offset 鼠標相對於元素的位置<BR>";
  ids.innerHTML += "offsetX =" + event.offsetX + "<BR>";
  ids.innerHTML += "offsetY =" + event.offsetY + "<BR>";
}
function screen(ids){
  ids.innerHTML = "scrollWidth =" + ids.scrollWidth + "<BR>";
  ids.innerHTML += "scrollHeight =" + ids.scrollHeight + "<BR>";
  ids.innerHTML += "scrollTop =" + ids.scrollTop + "<BR>";
  ids.innerHTML += "scrollLeft =" + ids.scrollLeft + "<BR>";
}
function client(ids){
  ids.innerHTML = "clientWidth =" + ids.clientWidth + "<BR>";
  ids.innerHTML += "clientHeight =" + ids.clientHeight + "<BR>";
  ids.innerHTML += "clientTop =" + ids.clientTop + "<BR>";
  ids.innerHTML += "clientLeft =" + ids.clientLeft + "<BR>";
}
function eventc(ids){
  ids.innerHTML = "鼠標相對於屏幕坐標<BR>event.screenX=" + event.screenX + "<BR>";
  ids.innerHTML += "event.screenY =" + event.screenY + "<BR>";
  ids.innerHTML += "鼠標相對於網頁坐標 event.clientX=" + event.clientX + "<BR>";
  ids.innerHTML += "event.clientY =" + event.clientY + "<BR>";
}
</script>
</body>
</html>

記憶要點

簡而言之:offset 系列相對於「父容器」,用於計算元素在文檔中的相對位置;client 系列代表「可見區域」的尺寸;scroll 系列對應「滾動」相關的量;而鼠標的 screen 是相對於整個屏幕,client 則相對於當前視窗。理解這幾組參照系的差異,才能在彈窗定位、拖拽、滾動加載等場景中游刃有餘。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved