DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> JavaScript獲取鼠標移動時的坐標(兼容IE8、chome谷歌、Firefox)
JavaScript獲取鼠標移動時的坐標(兼容IE8、chome谷歌、Firefox)
編輯:關於JavaScript     

JavaScript獲取鼠標移動時的坐標(兼容:IE8、谷歌、Firefox、Opera ),測試通過

直接復制成html文件,即可運行。

為方便大家測試特准備了一份在線演示

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<title>JavaScript獲取鼠標移動時的坐標(兼容:IE8、谷歌、Firefox、Opera)_</title> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
<style type="text/css"> 
.tip { 
width:200px; 
border:2px solid #ddd; 
padding:8px; 
background:#f1f1f1; 
color:#666; 
} 
</style> 
<script type="text/javascript"> 
 
//方法1 
function mousePos(e){ 
  var x,y; 
  var e = e||window.event; 
  return { 
    x:e.clientX+document.body.scrollLeft + document.documentElement.scrollLeft, 
    y:e.clientY+document.body.scrollTop + document.documentElement.scrollTop 
  }; 
}; 
 
//方法2 
//Firefox支持屬性pageX,與pageY屬性,這兩個屬性已經把頁面滾動計算在內了, 
//在Chrome可以通過document.body.scrollLeft,document.body.scrollTop計算出頁面滾動位移, 
//而在IE下可以通過document.documentElement.scrollLeft ,document.documentElement.scrollTop 
function getMousePos(event) { 
      var e = event || window.event; 
      var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; 
      var scrollY = document.documentElement.scrollTop || document.body.scrollTop; 
      var x = e.pageX || e.clientX + scrollX; 
      var y = e.pageY || e.clientY + scrollY; 
      //alert('x: ' + x + '\ny: ' + y); 
      return { 'x': x, 'y': y }; 
    } 
 
function test(e){ 
document.getElementById("mjs").innerHTML = getMousePos(e).x+','+getMousePos(e).y;   
}; 
</script> 
</head> 
<body> 
<div id="mjs" class="tip">獲取鼠標點擊位置坐標</div> 
<div id="test" style="width:1000px;height:1000px;background:#ccc;" onmousemove="test(event)"></div> 
</body> 
</html>
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved