0
<script type="text/javascript">
var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMousePos;
// Temporary variables to hold mouse x-y pos.s
var tempX = 30;
var tempY = 30;

function getMousePos(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/correct negative values 
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  

  // show the position values in the form
  document.MouseDisplay.MouseX.value = tempX;
  document.MouseDisplay.MouseY.value = tempY;
  return true;
}

// execute function
if (tempY < 30) {
 alert('tempY is found to be less than 30');
}

</script>

我在 hotscript 和 codelifter http://www.codelifter.com/main/javascript/capturemouseposition1.html找到了这段代码,它来自一个旧线程,但我相信它有我需要实现的目标。每当鼠标 Y 位置小于 30 时,我都想执行一个函数。

我是编程初学者,希望可以从这里的示例中慢慢学习。

我的问题是,为什么没有触发警报命令?我在这里想念什么。我做了一个简单的按钮来调用它起作用的功能。

<script type="text/javascript">
function myFunction() {
alert('tempY is found to be less than 30');
}
</script>
4

1 回答 1

0

没有尝试过您的代码,但假设它在鼠标移动时确实有效,要查看您的警报,只需在函数内移动该行:

var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
document.onmousemove = getMousePos;
// Temporary variables to hold mouse x-y pos.s
var tempX = 30;
var tempY = 30;

    function getMousePos(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/correct negative values 
      if (tempX < 0){tempX = 0}
      if (tempY < 0){tempY = 0}  

      // show the position values in the form
      document.MouseDisplay.MouseX.value = tempX;
      document.MouseDisplay.MouseY.value = tempY;

      // execute function
      if (tempY < 30) {
       alert('tempY is found to be less than 30');
      }
      return true;
    }
于 2012-08-08T13:10:56.847 回答