简体   繁体   中英

How to Trigger this Javascript Function

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

I found this code at hotscript and codelifter http://www.codelifter.com/main/javascript/capturemouseposition1.html , it was from an old thread but I believe it's got what I need to achieve. I want to execute a function whenever the mouse Y position is less than 30.

I'm a beginner at programming, hope that I can slowly learn from samples here.

My question is, why is the alert command not triggered? What am I missing here. I did a simple button to call the function it works tho.

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

Haven't tried your code but assuming it does work when the mouse moves, to see your alert just move that line inside the function :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM