Hiding the mouse cursor when idle using JavaScript

后端 未结 7 1868
灰色年华
灰色年华 2021-02-14 01:29

Is it possible to use JavaScript to set the cursor attribute to the property none if the mouse is inactive for a certain amount of time (say, five seco

7条回答
  •  既然无缘
    2021-02-14 02:33

    If anyone still looking for answer in 2019 (as did I), this approach works on FF 71 and Chrome 78:

    var DEMO = {
      INI: {
        MOUSE_IDLE: 3000
      },
      hideMouse: function() {
        $("#game").css('cursor', 'none');
        $("#game").on("mousemove", DEMO.waitThenHideMouse);
      },
      waitThenHideMouse: function() {
        $("#game").css('cursor', 'default');
        $("#game").off("mousemove", DEMO.waitThenHideMouse);
        setTimeout(DEMO.hideMouse, DEMO.INI.MOUSE_IDLE);
      },
      showMouse: function() {
        $("#game").off("mousemove", DEMO.waitThenHideMouse);
        $("#game").css('cursor', 'default');
      },
    };

    It's simple and clear. This version uses DEMO.hideMouse() to start hiding mouse and DEMO.showMouse() to cancel the event. Change #game to div of your choice ...

    It's more clear to work with on and off switch and named functions instead of lambdas.

    I know that OP didn't specify that answers using JQuery are expected, but in my experience: I am always happy to see different approaches to learn from.

提交回复
热议问题