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

时间:2012-06-28 12:54:19

标签: 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。

4 个答案:

答案 0 :(得分:8)

试试这个,这适用于所有浏览器,包括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>

答案 1 :(得分:6)

使用jQuery并使用event.pageX和event.pageY!

请参阅http://api.jquery.com/event.pageY/

答案 2 :(得分:4)

我用这段代码解决了这个问题

    var CurX;
    var CurY;
    var IE = document.all?true:false;
    if(IE){
        CurX = window.event.clientX;
        CurY = window.event.clientY;
    }
    else{
        if (window.captureEvents) {
        document.captureEvents(Event.MOUSEMOVE);
    }
    document.onmousemove = getCursorXY;
}

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);
}

答案 3 :(得分:0)

使用:clientX和clientY

喜欢这段代码:

var posx = 0;
var posy = 0;
if (e.pageX || e.pageY)     {
    posx = e.pageX;
    posy = e.pageY;
}
else if (e.clientX || e.clientY)    {
    posx = e.clientX + document.body.scrollLeft
        + document.documentElement.scrollLeft;
    posy = e.clientY + document.body.scrollTop
        + document.documentElement.scrollTop;
}