如何触发此Javascript函数

时间:2012-08-08 13:04:54

标签: javascript

<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>

1 个答案:

答案 0 :(得分:0)

Haven没有尝试过您的代码,但假设它在鼠标移动时起作用,看到您的警报只是在该函数内移动该行:

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