JavaScript gets the coordinates of when the mouse moves compatible with IE8 chome Google and Firefox

  • 2020-03-30 03:55:11
  • OfStack

JavaScript to get the coordinates of the mouse movement (compatibility: IE8, Google, Firefox, Opera), passed the test

Copy it directly into an HTML file and you're ready to run.

For the convenience of all test, prepared a (link: http://demo.jb51.net/js/2014/js_zuobiao.htm)


<!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 Gets the coordinates when the mouse moves ( Compatible with :IE8 , Google, Firefox , Opera)_ The home of the script </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"> 
 
//Method 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 
  }; 
}; 
 
//Method 2
//Firefox supports the properties pageX and pageY, which already count scrolling,
//In Chrome, you can calculate page scrolling displacement by document.body.scrollleft, document.body.scrolltop,
//And under the IE can through the document. The 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"> Gets the coordinates of where the mouse is clicked </div> 
<div id="test" style="width:1000px;height:1000px;background:#ccc;" onmousemove="test(event)"></div> 
</body> 
</html>

Related articles: