Detecting if the browser window is moved with JavaScript?

前端 未结 6 2106
庸人自扰
庸人自扰 2020-12-10 12:48

This is for a demo... and i was just curious, can you detect if the window has been moved? Like if you move Firefox/Chrome/IE around your monitor? I doubt it, but I wanted t

6条回答
  •  抹茶落季
    2020-12-10 13:23

    A potentially more optimised version of this is to only check for window movement when outside of the window combined with Harmen's answer:

    var interval;
    window.addEventListener("mouseout", function(evt){ 
      if (evt.toElement === null && evt.relatedTarget === null) {
        //if outside the window...
        if (console) console.log("out");
        interval = setInterval(function () {
          //do something with evt.screenX/evt.screenY
        }, 250);
      } else {
        //if inside the window...
        if (console) console.log("in");
        clearInterval(interval);
      }
    });
    

    If using jQuery, it may normalise screenX/Y in this case so it's worth running a few tests on that. Jquery would use this format instead of addEventListener:

    $(window).on('mouseout', function () {});
    

    If you are moving the window in Windows OS via alt + Space, and find that windows resizes are ignored, I would recommend adding an extra level of detection via keypress events.

提交回复
热议问题