javascript - 如何使用 Internet Explorer 的 javascript 获取鼠标指针位置?

标签 javascript javascript-events

我正在开发一个网页,我在 <div> 中设置了一个图像。动态地。 它在 Firefox 中有效,但在 IE 中失败。

问题是:如何在IE中获取鼠标指针位置? 我正在使用以下代码获取鼠标指针位置

function getCursorXY(e) {   
    CurX = (window.Event) ? e.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}

它在 Firefox 上运行良好。

最佳答案

试试这个,这应该适用于包括 IE 在内的所有浏览器。

<html>
<body>
<form name="Show">
<input type="text" name="MouseX" value="0" size="4"> X<br>
<input type="text" name="MouseY" value="0" size="4"> Y<br>
</form>

<script language="JavaScript1.2">
<!--

// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE)

// Set-up to use getMouseXY function onMouseMove
document.onmousemove = getMouseXY;

// Temporary variables to hold mouse x-y pos.s
var tempX = 0
var tempY = 0

// Main function to retrieve mouse x-y pos.s

function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  document.Show.MouseX.value = tempX
  document.Show.MouseY.value = tempY
  return true
}

//-->
</script>
</body>
</html>

关于javascript - 如何使用 Internet Explorer 的 javascript 获取鼠标指针位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245119/

相关文章:

javascript - 使用 javascript 下载文件并忽略 MIME

javascript - 如何使用栅格源类型?

javascript - jquery 为新创建的元素委托(delegate) onload 事件处理程序

javascript - 没有 JQuery 的鼠标输入

javascript-events - 如何在javascript中停止onChange

javascript - onClick 事件没有在 javaScript 中被调用

javascript - 使用 JavaScript/JQuery 将 html 表格数据导出到 Excel 在 chrome 浏览器中无法正常工作

javascript - 是拥有一个包含少量 JS 的大网页更好,还是拥有一个包含一些 JS 生成内容的小网页更好?

javascript-events - JavaScript 在运行时向事件添加多个函数